React折线图阴影(Chart.js)

mcvgt66p  于 2023-08-05  发布在  Chart.js
关注(0)|答案(1)|浏览(203)

我在React应用程序中使用react-chartjs-2库创建了多个图表。我正在使用Chart.register方法对折线图应用自定义阴影效果。但是,这会将阴影应用于所有图表组件。
下面是相关代码:

  1. import React, { useEffect } from 'react';
  2. import { Line } from 'react-chartjs-2';
  3. import { Chart, registerables } from 'chart.js';
  4. Chart.register(...registerables);
  5. const PriceGraph = ({ chartData, chartColour, chartFillColour }) => {
  6. const options = {
  7. plugins: {
  8. legend: {
  9. display: false,
  10. }
  11. },
  12. scales: {
  13. x: {
  14. grid: {
  15. display: true,
  16. drawBorder: true,
  17. drawOnChartArea: false,
  18. },
  19. ticks: {
  20. display: true,
  21. }
  22. },
  23. y: {
  24. grid: {
  25. display: false,
  26. drawBorder: true,
  27. drawOnChartArea: false,
  28. },
  29. ticks: {
  30. display: true,
  31. }
  32. }
  33. }
  34. }
  35. // Custom shadow for chart
  36. useEffect(() => {
  37. Chart.register({
  38. id: 'customShadow',
  39. beforeDraw: (chart) => {
  40. const ctx = chart.ctx;
  41. ctx.save();
  42. const originalLineDraw = ctx.stroke;
  43. ctx.stroke = function () {
  44. ctx.save();
  45. ctx.shadowColor = 'rgba(0, 0, 0, 0.2)';
  46. ctx.shadowBlur = 10;
  47. ctx.shadowOffsetX = 4;
  48. ctx.shadowOffsetY = 4;
  49. originalLineDraw.apply(this, arguments);
  50. ctx.restore();
  51. };
  52. }
  53. });
  54. }, []);
  55. const data = {
  56. labels: chartData.labels,
  57. datasets: [
  58. {
  59. data: chartData.data,
  60. backgroundColor: chartFillColour,
  61. borderColor: chartColour,
  62. fill: true,
  63. }
  64. ]
  65. }
  66. return chartData.labels ? <Line data={data} options={options}/> : null;
  67. }
  68. export default PriceGraph;

字符串
如何修改此代码以仅对PriceGraph组件呈现的折线图应用阴影效果,而不影响应用程序中的其他图表组件?
如果你能帮忙的话,我将不胜感激。谢谢你,谢谢

dwbf0jvd

dwbf0jvd1#

如果您注册了插件,则此插件将用于应用程序中的所有图表示例。你应该将它设置为一个“内联”插件,在你想要使用它的图表示例中(希望react-chartjs-2语法是正确的):

  1. const myPlugin = {
  2. id: 'customShadow',
  3. beforeDraw: (chart) => {
  4. const ctx = chart.ctx;
  5. ctx.save();
  6. const originalLineDraw = ctx.stroke;
  7. ctx.stroke = function () {
  8. ctx.save();
  9. ctx.shadowColor = 'rgba(0, 0, 0, 0.2)';
  10. ctx.shadowBlur = 10;
  11. ctx.shadowOffsetX = 4;
  12. ctx.shadowOffsetY = 4;
  13. originalLineDraw.apply(this, arguments);
  14. ctx.restore();
  15. };
  16. }
  17. };
  18. return chartData.labels ? <Line data={data} options={options} plugins={[myPlugin]}/> : null;

字符串

展开查看全部

相关问题