I am using chartsJS to show a pie chart. 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:
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>