score:4

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

        // and then we put the fillstyle back to its previous value
        ctx.fillstyle = prevfillstyle;                                              
    }                                
};

and here is the final result : enter image description here

score:0

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

Related Query

More Query from same tag