能否基于数据集项为Chart.js图表设置背景颜色?
在Chart.js中基于数据集项动态设置背景色
完全可以通过backgroundColor的回调函数实现需求,利用回调参数context提供的索引值,关联你的原始数据集即可获取对应颜色。
修改后的实现代码
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: (context) => { // 通过dataIndex获取当前数据项在原始数据集里的对应条目 const item = dataSet[context.dataIndex]; // 兼容数据集中字段名不一致的情况 return item.colour || item.color; } }] } })
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <canvas id="chart"></canvas>
关键说明
- 回调函数的
context参数包含当前数据项的索引dataIndex,该索引与你从dataSet映射得到的scores数组索引完全对应,因此可以直接用它从原始dataSet中取出对应条目。 - 代码中兼容了数据集中字段名不一致的问题(Alice的颜色字段为
color而非colour),避免渲染异常。
内容的提问来源于stack exchange,提问作者Sajad Torkamani
相关产品推荐
相关产品推荐

