I was looking at this code and added ctx.fillStyle = ‘red’, and got this. I click on eBooks to hide its data but instead of eBooks being red, Microforms and Audiovisuals Mats were changed to red.
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(); ctx.fillStyle = 'red'; //added here } };
Advertisement
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; } };