[Chartjs]-Chart.js pie chart background colors: is there any way to generate them randomly?

5👍

No, chartjs does not come with this option.

I guess you have two options:

  • If you know a maximum (Ex: There won’t be more than 10 values), then you can make an array with 10 colors and assign the first colors to the elements you have (Ex: If you have 5 elements, assign the first 5 colors to them). You could easily randomize for example where in the array does the assignment start, to still get a different color set every time.

    This method if good if you want to keep your colors to match a specific color theme.

  • If you do not care about a color theme, I think the easiest would be to generate the colors randomly. With this function, you can only hope to not get twice the same color (very very unlikely):

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

console.log(getRandomColor());

Leave a comment