如何修改Chart.js饼图切片内计数数字的字体颜色
修改Chart.js饼图切片内数字的字体颜色
要修改饼图切片内的计数数字字体颜色,你需要用到chartjs-plugin-datalabels插件(原生Chart.js并未内置切片内数据标签功能),具体配置如下:
先确保已安装并引入插件:
- npm安装:
npm install chartjs-plugin-datalabels - 或通过CDN引入:
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
- npm安装:
在你的options配置中添加
datalabels插件配置,通过color属性设置字体颜色:
// 如果使用模块引入,先导入插件 import ChartDataLabels from 'chartjs-plugin-datalabels'; const options = { plugins: { legend: { display: true, labels: { usePointStyle: true, pointStyle: "rectRounded", }, }, title: { display: false, text: "Use of App", }, tooltip: { callbacks: { label: function (context) { const label = context.label || ""; const value = context.parsed; const total = context.dataset.data.reduce( (a, b) => a + b, 0 ); const percentage = calculatePercentage(value, total); return `${label}: ${value} (${percentage})`; }, }, }, // 配置数据标签插件 datalabels: { color: '#ffffff', // 这里设置你需要的字体颜色,支持十六进制、RGB、颜色名称 font: { weight: 'bold', // 可选:设置字体粗细 size: 14 // 可选:设置字体大小 }, formatter: (value) => value // 自定义显示内容,这里直接显示数值 } }, // 注册插件(全局注册过的话可省略) plugins: [ChartDataLabels] };
- 如果需要给不同切片设置不同颜色,可以将
color设为函数:
datalabels: { color: (context) => { // 根据切片索引返回对应颜色 const colorList = ['#000', '#fff', '#ff4444', '#4CAF50']; return colorList[context.dataIndex % colorList.length]; }, // 其他配置... }
内容的提问来源于stack exchange,提问作者jquin
相关产品推荐
相关产品推荐

