Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearRect does not clear the canvas when drawing vertical lines

I hit a weird edge case building something with canvas at work. clearRect does not clear the canvas when drawing vertical lines that go from the top to the bottom of the canvas. When rendering other stuff, clearRect works fine.

I'm not sure if I am missing something obvious, if this is intentional behavior, or a browser bug (unlikely since the behavior is identical in chrome, safari, firefox and opera on mac). If it is intentional behavior, does anybody know the rationale behind it and/or can perhaps point to some documentation?

I made a small test case that shows the behavior clearly, only the combination clearRect/vertical lines does not clear the canvas: http://jsfiddle.net/kZj6F/

Thanks!

like image 203
bwindels Avatar asked Mar 14 '12 11:03

bwindels


People also ask

How do you clear canvas and redraw?

We can clear the canvas easily with the clearRect method, which is part of the canvas context object. to draw something and add a click listener to the button to clear the canvas when we click the button. We call getContext to get the context object.

How do you clear a rectangular canvas?

clearRect() The CanvasRenderingContext2D. clearRect() method of the Canvas 2D API erases the pixels in a rectangular area by setting them to transparent black.


1 Answers

Your issue is with a missing beginPath causing subsequent lines to be added to the same path that was stroke drawing all lines.

If you switch to dots and back to lines with the clearRect option choose you can see the last arc added to the path being drawn too. Just add a call ctx.beginPath(); prior ctx.moveTo(randomX + 0.5, 0); ctx.lineTo(randomX + 0.5, canvas.height); and the problem is solved.

You can check http://jsfiddle.net/kZj6F/1/ to see it working.

Bwt it will with other shapes too if they got added to the path and the path was not cleared.

like image 50
Prusse Avatar answered Oct 23 '22 12:10

Prusse