我知道在Chart.js中,您可以将一组 colored颜色 传递给backgroundColor
option,但是否可以使用当前的dataset
项来 Select colored颜色 ?理想情况下,我想做一些类似的事情:
new Chart(ctx, {
type: "pie",
data: {
datasets: [{
data: scores,
backgroundColor: (context) => {
// This is the key bit. Can I somehow access the current
// dataset item here from the context?
return context.item.colour
}
}]
}
})
下面是一个工作示例,其中backgroundColor
是一个数组,但我想将其更改为使用一个回调函数来设置基于当前数据集项的背景:
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 scores = dataSet.map(data => data.score)
new Chart(ctx, {
type: "pie",
data: {
datasets: [{
data: scores,
backgroundColor: ['red', 'green', 'blue'] // Is there a way I can choose the colour based on the dataset item. Ideally, I'd want to access the array item from dataSet and read the `colour` property from there.
}]
}
})
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="chart"></canvas>