1

I'm using chart JS to draw a pie chart with some data from the database. The problem is I don't know how many elements may appear on the chart, so generating the background colors its a bit difficult.

Is there any option so chart js would randomly generate those colors?

petekaner
  • 8,071
  • 5
  • 29
  • 52
  • You could check my answer at [here](https://stackoverflow.com/questions/28828915/how-set-color-family-to-pie-chart-in-chart-js/48589545#48589545) – Conny Olsson Feb 27 '18 at 20:17

1 Answers1

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());
Community
  • 1
  • 1
nicovank
  • 3,157
  • 1
  • 21
  • 42