【问题标题】:change legend item style when dataset is hidden隐藏数据集时更改图例项样式
【发布时间】:2017-03-04 05:25:28
【问题描述】:

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

感谢您的帮助

【问题讨论】:

  • 您的问题已得到正确回答。

标签: chart.js


【解决方案1】:

不幸的是,如果您打算使用 chart.js 提供的自动生成的图例,则没有真正简单的方法可以做到这一点。不过有可能。

如果你通读source,你会发现删除线实际上是在画布对象中渲染的(如下图)。

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 函数并进行小改动。

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)。

如果您想做的不仅仅是使文本变亮,那么我强烈建议您实现自己的自定义外部图例。您可以使用legendCallback 配置选项和.generateLegend() 原型方法来做到这一点。

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

【讨论】:

  • 很棒,但是否可以在 react-chartjs-2 中重现相同的行为?
【解决方案2】:

查看文档的这一部分: http://www.chartjs.org/docs/#chart-configuration-legend-configuration

我希望这会有所帮助。

【讨论】:

  • 谢谢,我已经看过了,但没有说明如何更改样式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 2011-10-01
  • 2018-08-26
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多