React折线图阴影(Chart.js)

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

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

import React, { useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

const PriceGraph = ({ chartData, chartColour, chartFillColour }) => {

  const options = {
    plugins: {
      legend: {
        display: false,
      }
    },
    scales: {
      x: {
        grid: {
          display: true,
          drawBorder: true,
          drawOnChartArea: false,
        },
        ticks: {
          display: true,
        }
      },
      y: {
        grid: {
          display: false,
          drawBorder: true,
          drawOnChartArea: false,
        },
        ticks: {
          display: true,
        }
      }
    }
  }

  // Custom shadow for chart
  useEffect(() => {
    Chart.register({
      id: 'customShadow',
      beforeDraw: (chart) => {
        const ctx = chart.ctx;
        ctx.save();

        const originalLineDraw = ctx.stroke;
        ctx.stroke = function () {
          ctx.save();
          ctx.shadowColor = 'rgba(0, 0, 0, 0.2)';
          ctx.shadowBlur = 10;
          ctx.shadowOffsetX = 4;
          ctx.shadowOffsetY = 4;
          originalLineDraw.apply(this, arguments);
          ctx.restore();
        };
      }
    });
  }, []);

  const data = {
    labels: chartData.labels,
    datasets: [
      {
        data: chartData.data,
        backgroundColor: chartFillColour,
        borderColor: chartColour,
        fill: true,
      }
    ]
  }

  return chartData.labels ? <Line data={data} options={options}/> : null;
}

export default PriceGraph;

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

dwbf0jvd

dwbf0jvd1#

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

const myPlugin = {
      id: 'customShadow',
      beforeDraw: (chart) => {
        const ctx = chart.ctx;
        ctx.save();

        const originalLineDraw = ctx.stroke;
        ctx.stroke = function () {
          ctx.save();
          ctx.shadowColor = 'rgba(0, 0, 0, 0.2)';
          ctx.shadowBlur = 10;
          ctx.shadowOffsetX = 4;
          ctx.shadowOffsetY = 4;
          originalLineDraw.apply(this, arguments);
          ctx.restore();
        };
      }
    };

return chartData.labels ? <Line data={data} options={options} plugins={[myPlugin]}/> : null;

字符串

相关问题