2👍
The way you want to access the color in the scriptable option you need to pass your dataset as is to chart.js and use the parsing option in the config to tell chart.js in which field in your object the data is it has to show:
const ctx = document.getElementById('chart')
const dataSet = [{
name: 'John',
score: 10,
colour: 'orange'
},
{
name: 'Bob',
score: 5,
colour: 'yellow',
},
{
name: 'Alice',
score: 20,
colour: 'pink'
}
]
new Chart(ctx, {
type: "pie",
data: {
datasets: [{
data: dataSet,
backgroundColor: (c) => c.raw.colour,
}]
},
options: {
parsing: {
key: 'score'
}
}
})
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="chart"></canvas>
1👍
You could use map()
to generate an array of colors base on dataSet
:
backgroundColor: dataSet.map(({ colour }) => colour)
But you could also use reduce()
to re-work your dataSet
variable to the format CharJS expects. Then you don’t need the map()
for the score :
const ctx = document.getElementById('chart')
const dataSet = [
{ name: 'John', score: 10, colour: 'orange' },
{ name: 'Bob', score: 5, colour: 'yellow', },
{ name: 'Alice', score: 20, color: 'pink' }
]
const mappedDataSet = dataSet.reduce((p, { score, colour }) => {
p.data.push(score);
p.backgroundColor.push(colour);
return p;
}, { data: [], backgroundColor: [] });
new Chart(ctx, {
type: "pie",
data: {
datasets: [ mappedDataSet ]
}
})
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="chart"></canvas>
0👍
Chart.js Background Colour Issue
To use a callback function to set the backgroundColor
based on the current dataset item you can make use of the context parameter that is passed to the callback. For your specific need you can use the context.dataIndex
to get the current data point’s index and then access the relevant color from the dataSet
array.
Example Usage:
const ctx = document.getElementById('chart').getContext('2d');
const dataSet = [{
name: 'John',
score: 10,
color: 'orange'
},
{
name: 'Bob',
score: 5,
color: 'yellow'
},
{
name: 'Alice',
score: 20,
color: 'pink'
}
];
const scores = dataSet.map(data => data.score);
new Chart(ctx, {
type: "pie",
data: {
labels: dataSet.map(data => data.name),
datasets: [{
data: scores,
backgroundColor: (context) => {
return dataSet[context.dataIndex].color;
}
}]
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js Dynamic Color</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="chart"></canvas>
</body>
</html>