I am trying to draw a pie chart using Chart.js. My values are coming from a database hence I don\'t know how many values there are going to be in the database. Here I want t
Don't waist your time creating a random generator. Instead, pick a few bright pretty colors to loop through.
This function takes any size and builds an array of background colors using the pallet array.
function getColors(length){
let pallet = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
let colors = [];
for(let i = 0; i < length; i++) {
colors.push(pallet[i % pallet.length]);
}
return colors;
}
You can then set your background colors by calling this function, passing the size of your data as a parameter.
datasets:
[
{
data: data,
backgroundColor: getColors(data.length)
}
]
This way your colors are always pretty and every data element is assigned a value.