[Chartjs]-Change legend item style when dataset is hidden

6👍

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.

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

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

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

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.

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.

-6👍

Take a look at this part of the documentation:
http://www.chartjs.org/docs/#chart-configuration-legend-configuration

I hope this helps.

Leave a comment