嘿,我正在使用很棒的 Chart.js 库,我想自定义图例项的样式。现在,当数据集被隐藏时,在图例中我们可以看到一条线。例如,我想设置文本不透明度。请问这个怎么改?
谢谢你的帮助
不幸的是,如果您打算使用 chart.js 提供的自动生成的 Legend,则没有真正简单的方法可以做到这一点。不过也有可能。
如果你通读源码,你会发现删除线其实是渲染在canvas对象中的(如下图)。
var fillText = function(x, y, legendItem, textWidth) {
ctx.fillText(legendItem.text, boxWidth + (fontSize / 2) + x, y);
if (legendItem.hidden) {
// Strikethrough the text if hidden
ctx.beginPath();
ctx.lineWidth = 2;
ctx.moveTo(boxWidth + (fontSize / 2) + x, y + (fontSize / 2));
ctx.lineTo(boxWidth + (fontSize / 2) + x + textWidth, y + (fontSize / 2));
ctx.stroke();
}
};
Run Code Online (Sandbox Code Playgroud)
因此,要更改该行为,您必须通过扩展 Chart.Legend 并实现您自己的draw
功能来自己实现它。由于您只关心更改这个小细节,您可以简单地复制 Chart.Legenddraw
函数并进行小更改。
var fillText = function(x, y, legendItem, textWidth) {
if (legendItem.hidden) {
// lighten the hidden text
ctx.fillStyle = Chart.helpers.color(fontColor).lighten(0.75).rgbString();
}
ctx.fillText(legendItem.text, boxWidth + (fontSize / 2) + x, y);
// restore the original fillStyle so we dont impact the rest of the labels
ctx.fillStyle = fontColor;
};
Run Code Online (Sandbox Code Playgroud)
这是一个代码笔,演示了我的意思(显示了如何正确扩展 Chart.Legend)。
如果您想做一些更奇特的事情而不仅仅是使文本变亮,我强烈建议您实现自己的自定义外部图例。您可以使用legendCallback
config 选项和.generateLegend()
原型方法来做到这一点。
这是另一个演示自定义外部图例的代码笔。由于图例现在位于画布对象的外部,因此您可以使用 css 和 javascript 随意设置样式。