Search code examples
javascriptreactjschart.jsreact-chartjsreact-chartjs-2

Background color of the chart area in chartjs not working


I wanted to color the chart area of my line graph however it's not working:

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

I have also recreated this in codesandbox: https://codesandbox.io/s/practical-shadow-9he5y?file=/src/App.js:914-1118


Solution

  • I forked a sandbox from yours : React Chartjs Canvas Background

    You can register plugins in 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();
      }
    });
    

    }, []);

    Also additional useful resources for you :

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

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