admin管理员组文章数量:1431994
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
1 Answer
Reset to default 5No, 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());
版权声明:本文标题:javascript - chart.js pie chart background colors: is there any way to generate them randomly? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745537837a2662353.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论