30đź‘Ť
With v2.1 of Chart.js, you can write your own plugin to do this
Preview
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/
- [Chartjs]-Chart.js – How to display title in multiple lines?
- [Chartjs]-Can't change color line with chart.js
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.
- [Chartjs]-Is it possible to produce circular (round) shaped radar chart in Chart.js?
- [Chartjs]-Property 'getContext' does not exist on type 'HTMLElement'
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.