chartjs 中图表区域的背景颜色不起作用

Background color of the chart area in chartjs not working

我想为折线图的图表区域着色,但它不起作用:

options={{
          maintainAspectRatio: false,
          title: {
            display: true,
            fontSize: 20
          },
          chartArea: {
            backgroundColor: "blue"
          },

我也在codesandbox中重新创建了这个: https://codesandbox.io/s/practical-shadow-9he5y?file=/src/App.js:914-1118

没有 chartArea.backgroundColor 选项,您需要为此使用自定义插件:

const plugin = {
  id: 'background',
  beforeDraw: (chart, args, opts) => {
    if (!opts.color) {
      return;
    }

    const {
      ctx,
      chartArea
    } = chart;

    ctx.fillStyle = opts.color;
    ctx.fillRect(chartArea.left, chartArea.top, chartArea.width, chartArea.height)
  }
}

Chart.register(plugin);

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    plugins: {
      background: {
        color: 'cyan'
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

我从你那里 fork 了一个沙箱: React Chartjs Canvas Background

你可以在useEffect中注册插件:

useEffect(() => {
Chart.register({
  id: "custom_canvas_background_color",
  beforeDraw: (chart) => {
    console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    const ctx = chart.canvas.getContext("2d");
    ctx.save();
    ctx.globalCompositeOperation = "destination-over";
    ctx.fillStyle = "lightGreen";
    ctx.fillRect(0, 0, chart.width, chart.height);
    ctx.restore();
  }
});

}, []);

还有其他对您有用的资源:

https://github.com/reactchartjs/react-chartjs-2

https://github.com/chartjs/Chart.js/tree/v3.5.1