You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否基于数据集项为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:03:20