Accepted answer

If you take a look at the fillStyle doc on MDN :

The CanvasRenderingContext2D.fillStyle property of the Canvas 2D API specifies the color or style to use inside shapes.

So it will have an effect on the next shapes (such as text via fillText).

You need to change the style of the text before writing it down.

Using the same function you put in your question :

var fillText = function(x, y, legendItem, textWidth) 
    // We store the current fillStyle
    var prevFillStyle = ctx.fillStyle;

    if (legendItem.hidden) {
        // If the item is hidden, we change the fillStyle to red
        ctx.fillStyle = "red";

    // The legend label is written here
    ctx.fillText(legendItem.text, boxWidth + (fontSize / 2) + x, y);

    if (legendItem.hidden) {
        // We comment the stroke part -- as you did
        //ctx.lineWidth = 2;
        //ctx.moveTo(boxWidth + (fontSize / 2) + x, y + (fontSize / 2));
        //ctx.lineTo(boxWidth + (fontSize / 2) + x + textWidth, y + (fontSize / 2));

        // And then we put the fillStyle back to its previous value
        ctx.fillStyle = prevFillStyle;                                              

And here is the final result : enter image description here


I found a better way doing that:

add onClick to legends and put this :

      const index = legendItem.datasetIndex;
      const ci = legend.chart;
      const isVisible = ci.isDatasetVisible(index);
      ci.setDatasetVisibility(index, !isVisible);

      // this is where the stroke remove happens
      const ci = legend.chart;

      const fillTextValue = ci.ctx.fillText;
      ci.ctx.fillText = function fillText(x, v, b) {
        fillTextValue.bind(ci.ctx, x, v, b)();
        this.fillStyle = "rgba(0,0,0,0)"; // whatever color you like

Related Query

More Query from same tag