Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear line on HTML5 Canvas

Is there a way to unstroke a line? On my canvas I have a line with opacity 0.5, and width of 20 pixels, let's say. Now I want to to make it longer, means to draw another line right out of the old one. when doing that, the matching points between the old and the new lines become less transparent (because they're made of two lines now). so I want to unstroke the old line and then stroke the new one.

how can I do it?

thanks

like image 859
Amit Hagin Avatar asked Jul 08 '11 19:07

Amit Hagin


4 Answers

clearRect() is the only way to do it. A good way to work around this (if you have a lot of elements drawn on your canvas) is to overlay two canvases in the HTML using absolute positioning, using one for the "static" drawing and a top layer for the drawing that you plan to clear/redraw. This saves CPU time drawing all of your canvas again, too.

like image 109
therin Avatar answered Sep 30 '22 06:09

therin


Another elegant option is to set the 'globalCompositeOperation' to 'xor' and paint you line again....so it will be removed

like image 28
Alex Avatar answered Sep 30 '22 07:09

Alex


How you draw to a canvas is strictly defined by the API, but how it is done in software and/or hardware is up to the browser developers. Some of the browser using hardware acceleration and the others are working on it atm. (eg. using a software renderer atm)

In computer graphics when drawing something, you draw to a buffer. And when you call lineTo and stroke the buffer is updated and all information that were in the underlying pixels are lost (or partly lost if you use transparency) and there is no way to get it back by undoing (unless there is an implementation containing loads of old drawings, but that would be really heavy for the memory).

So to be able to undo a stroke might save alot of CPU/GPU time BUT whould heavily increase the memory

like image 35
Rickard Avatar answered Sep 30 '22 08:09

Rickard


I suppose the easiest way would be to simply clear the entire canvas (using clearRect) and just draw the whole line again

like image 30
Jani Hartikainen Avatar answered Sep 30 '22 06:09

Jani Hartikainen