简体   繁体   English

饼图的每个部分在chartsjs中随机颜色

[英]each section of a pie chart to a random color in chartsjs

I am using chartsJS to show a pie chart.我正在使用 chartsJS 来显示饼图。 I each time the page refreshes the chart will have a different number of sections.我每次页面刷新图表都会有不同数量的部分。 I am trying to set each section to a random color.我试图将每个部分设置为随机颜色。

I ac create a random colour no problem by:我通过以下方式创建随机颜色没问题:

<script>
const randomNum = () => Math.floor(Math.random() * (235 - 52 + 1) + 52);
const randomRGB = () => `rgb(${randomNum()}, ${randomNum()}, ${randomNum()})`;
</script>

I can then set the pie chart sections to this color by using:然后我可以使用以下方法将饼图部分设置为这种颜色:

backgroundColor: randomRGB(),

The whole pie chart turns the random color.整个饼图变成随机颜色。 How can I declare a loop that will set each section of the pie to a random color.如何声明一个循环,将饼图的每个部分设置为随机颜色。 note the number of pie sections will often change.请注意,饼图部分的数量经常会发生变化。

You can use a scriptable option for the backgroundColor for this:为此,您可以为 backgroundColor 使用可编写脚本的选项:

 const randomNum = () => Math.floor(Math.random() * (235 - 52 + 1) + 52); const randomRGB = () => `rgb(${randomNum()}, ${randomNum()}, ${randomNum()})`; const options = { type: 'pie', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: () => (randomRGB()) }] }, options: {} } const ctx = document.getElementById('chartJSContainer').getContext('2d'); new Chart(ctx, options);
 <body> <canvas id="chartJSContainer" width="600" height="400"></canvas> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM