[Chartjs]-Background colour of line charts in chart.js

30đź‘Ť

With v2.1 of Chart.js, you can write your own plugin to do this


Preview

enter image description here


Script

Chart.pluginService.register({
    beforeDraw: function (chart, easing) {
        if (chart.config.options.chartArea && chart.config.options.chartArea.backgroundColor) {
            var helpers = Chart.helpers;
            var ctx = chart.chart.ctx;
            var chartArea = chart.chartArea;

            ctx.save();
            ctx.fillStyle = chart.config.options.chartArea.backgroundColor;
            ctx.fillRect(chartArea.left, chartArea.top, chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
            ctx.restore();
        }
    }
});

and then

...
options: {
    chartArea: {
        backgroundColor: 'rgba(251, 85, 85, 0.4)'
    }
}
...

Fiddle – http://jsfiddle.net/rrcd60y0/

4đź‘Ť

I’m not sure what you mean by “the background color of the main area of the graph that isn’t occupied with the line chart”, but you can set the background-color of the canvas via CSS:

#myChart {
  background-color: #666;
}

Look at this fiddle to see how it affects the chart.

This will set the background for the whole canvas, if you only want to set it for the inner part, check out potatopeelings solution.

2đź‘Ť

Just to help others who are thinking how to add multiple background colors:
I modified a little bit @potatopeelings answer. First I checked how many columns there are

var columnCount = chart.data.datasets[0].data.length;
var width = chartArea.right - chartArea.left;
var columnWidth = width/columnCount;

and then fill every other of them with background color

while (startPoint < chartArea.right) {
    ctx.fillRect(startPoint, chartArea.top, columnWidth, height);
    startPoint += columnWidth * 2;
}

For my chart this works better but for this the July column is for some reason only part of it. Doesn’t know how to fix that but hopefully you can get idea from here.

http://jsfiddle.net/e7oy6yk6/2

Leave a comment