6👍
✅
Using Chart.js plugins, you can create your own backgroundColor
& borderColor
properties and then assign them to the chart :
var randomColorPlugin = {
// We affect the `beforeUpdate` event
beforeUpdate: function(chart) {
var backgroundColor = [];
var borderColor = [];
// For every data we have ...
for (var i = 0; i < chart.config.data.datasets[0].data.length; i++) {
// We generate a random color
var color = "rgba(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ",";
// We push this new color to both background and border color arrays
// .. a lighter color is used for the background
backgroundColor.push(color + "0.2)");
borderColor.push(color + "1)");
}
// We update the chart bars color properties
chart.config.data.datasets[0].backgroundColor = backgroundColor;
chart.config.data.datasets[0].borderColor = borderColor;
}
};
You can see a working example on this jsFiddle. Every time you run the code, you’ll get different colors.
Here is one of the result :
Source:stackexchange.com