[Chartjs]-Background color of the chart area in chartjs not working

0๐Ÿ‘

โœ…

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

1๐Ÿ‘

There is no chartArea.backgroundColor option, you will need to use a custom plugin for this:

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>

Leave a comment