-1

I am trying to use a canvas as a semi-transparent overlay with cutouts over an img tag. I can get the overlay to work, but for some reason clearRect(x,y,width,height) does not put the cutouts in the overlay so the image shows through the overlay. However, I can fill a rectangle with "clear" to make a cutout using fillRect, so I think my code is working. I don't understand why clearRect does not work.

The web page uses django and bootstrap 4. I created a jsfiddle with all the ajax and template tags removed to illustrate the problem. When your mouse hovers over the button 'hover here', the overlay appears but only one cutout is displayed - the one using fillRect, but not the one using clearRect. This happens in both Firefox and Chrome browsers.

What am I doing wrong with the clearRect call?

Thanks!

Mark

UPDATE: I tried to use fillText to write on my canvas, and that is not working as well. What am I doing wrong with my canvas that prevents clearRect and fillText from working? I updated the jsfiddle to reflect the fillText problem.

user1045680
  • 815
  • 2
  • 9
  • 19

1 Answers1

0

So, I discovered how to make the code in the jsfiddle work, but I still don't understand why.

If I add these lines to the initialization of the canvas, everything works.

canvas.height = image.height;
canvas.width = image.width;

I had thought the lines

canvas.style.left = position.left + "px";
canvas.style.top = position.top + "px";
canvas.style.width = image.width + "px";
canvas.style.height = image.height + "px";

took care of initializing the canvas size, since I don't know the size of the image until the page is loaded.

If anyone can explain why this fix makes the clearRect and fillText work, please explain!

New fiddle that works. See the comments at the end of the script.

user1045680
  • 815
  • 2
  • 9
  • 19