隐藏数据集时更改图例项样式 [英] change legend item style when dataset is hidden

查看:54
本文介绍了隐藏数据集时更改图例项样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在使用很棒的Chart.js库,我想自定义图例项目的样式。
现在,当隐藏数据集时,在图例中我们可以看到一条线。
我想例如设置文本不透明度。
如何更改呢?

Hey I'm using the awesome Chart.js library and I would like to customize the style of the legend item. For now, when dataset is hidden, in the legend we can see a line through. I would like to set text opacity for example instead. How to change this please ?

感谢您的帮助

推荐答案

不幸的是,如果您打算使用chart.js提供的自动生成的图例,则没有真正简单的方法来执行此操作。

Unfortunately, there is no real easy way to do this if you are planning to use the automatically generated Legend that chart.js provides. It is possible though.

如果您通读,您会发现删除线实际上是在canvas对象中呈现的(如下所示)。

If you read through the source, you will find that the strikethrough is actually rendered in the canvas object (as shown below).

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();
  }
};

因此,要更改该行为,您必须通过扩展Chart.Legend并实现自己的行为来实现 draw 函数。由于只关心更改次要细节,因此只需复制Chart.Legend draw 函数并进行小的更改。

Therefore, to change that behavior you have to implement it yourself by extending Chart.Legend and implementing your own draw function. Since you only care about changing this minor detail, you can simply copy the Chart.Legend draw function and make your small change.

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;
};

这里是 codepen 恰好说明了我的意思(显示了如何正确扩展Chart.Legend)。

Here is a codepen demonstrating exactly what I mean (shows how to correctly extend Chart.Legend).

除了简化文字之外,我还更建议您实现自己的自定义外部图例。您可以使用 legendCallback 配置选项,并使用 .generateLegend() 原型方法。

In case you want to do something more fancy than just lightening the text, I would highly recommend you implement your own custom external legend. You can do this with the legendCallback config option and using the .generateLegend() prototype method.

这里是另一个 codepen ,用于演示自定义的外部图例。由于图例现在位于画布对象的外部,因此可以使用css和javascript对其进行样式设置,以使其适合您的样式。

Here is another codepen that demonstrates a custom external Legend. Since the legend is now external to the canvas object, you can style it however you see fit using css and javascript.

这篇关于隐藏数据集时更改图例项样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆