最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - chart.js pie chart background colors: is there any way to generate them randomly? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Nov 10, 2016 at 21:08 petekanerpetekaner 8,9316 gold badges33 silver badges54 bronze badges 1
  • You could check my answer at here – Conny Olsson Commented Feb 27, 2018 at 20:17
Add a ment  | 

1 Answer 1

Reset to default 5

No, chartjs does not e 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());

发布评论

评论列表(0)

  1. 暂无评论