Chartjs-Chartjs area background color

1👍

You need to implement a plugin to fill the canvas.
Below a sample with fixed colors.

You can also have a look to the CHart.js sample: https://www.chartjs.org/docs/latest/samples/plugins/quadrants.html

const ctx = document.getElementById("myChart");
const plugin = {
  id: 'bgColorArea',
  beforeDraw(chart, args, options) {
    const {ctx, chartArea: {left, top, width, bottom}, scales: {x, y}} = chart;
    const endTop = y.getPixelForValue(35);
    const endMid = y.getPixelForValue(10);
    ctx.save();
    ctx.fillStyle = 'lightCoral';
    ctx.fillRect(left, top, width, endTop - top);
    ctx.fillStyle = 'lightGreen';
    ctx.fillRect(left, endTop, width, endMid - endTop);
    ctx.fillStyle = 'lightGrey';
    ctx.fillRect(left, endMid, width, bottom - endMid);
    ctx.restore();
  }
};
const myChart = new Chart(ctx, {
   type: 'line',
   plugins: [plugin],
   data: {
     labels: ['January', 'Fabruary', 'March', 'April', 'May', 'June', 'July'],
     datasets: [{
       label: 'test',
       data: [50, 35, 45, 47, 10, 3, 27],
       borderWidth: 2,
       borderColor: 'black'
     }]
   }
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment