我想在图表中的数据标签中将字体颜色设置为字符级别(或单词级别)。请看下面的图片前后。
例如,如果我的数据标签是0.89,我希望把0画成黄色,8画成蓝色,9画成红色。

沙箱:https://codesandbox.io/s/quizzical-hooks-zcg91?file=/src/components/LineChart.jsx
发布于 2021-08-05 15:22:17
Afaik您可以用数据标记插件设置字母的单个collors,为此您需要编写自己的自定义插件,您可以做的是为color属性提供一个collors数组,为每个条目提供一个不同的collor:https://codesandbox.io/s/dazzling-leaf-pxmzm
datalabels: {
display: true,
color: ["black", "green", "blue", "pink", "purple"],
align: "end",
padding: {
right: 2
},
labels: {
padding: { top: 10 },
title: {
font: {
weight: "bold"
}
}
},
formatter: function (value) {
return "\n" + value;
}
}编辑:
在查看数据标记插件用于呈现标签的代码之后,如果您需要编写自己的自定义插件,则无法对单个字符着色:
const customDatalabalesPlugin = {
id: 'customDatalabels',
afterDatasetsDraw: (chart, args, opts) => {
const {
ctx,
_metasets
} = chart;
_metasets.forEach((meta) => {
meta.data.forEach((datapoint) => {
const lineHeight = ctx.measureText('M').width;
const dpVal = datapoint.parsed.y;
const text = dpVal.toString();
const textWidth = ctx.measureText(text).width;
const color = opts.color || 'black';
if (typeof color === 'string') {
ctx.fillStyle = color;
ctx.fillText(text, (datapoint.x - textWidth / 2), (datapoint.y - lineHeight));
} else if (Array.isArray(color)) {
let x = datapoint.x - textWidth / 2;
for (let i = 0; i < text.length; i++) {
const char = text.charAt(i);
ctx.fillStyle = color[i % color.length];
ctx.fillText(char, x, (datapoint.y - lineHeight));
x += ctx.measureText(char).width;
}
} else {
console.error('Invalid color type provided');
}
})
})
}
}
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12.4, 19.234, 3.23213, 5.4, 2, 3],
borderColor: 'pink'
}]
},
options: {
plugins: {
customDatalabels: {
color: ['pink', 'green', 'orange'], // Color each character individual collor
// color: 'pink' // Color whole label this collor
}
}
},
plugins: [customDatalabalesPlugin]
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>
https://stackoverflow.com/questions/68669026
复制相似问题