The solution I found is to clear the whole canvas, but I only want to delete one line not all drawings on the canvas.
What should I do?
The solution I found is to clear the whole canvas, but I only want to delete one line not all drawings on the canvas.
What should I do?
There's no simple way to do that, as the previous information of the pixels are lost after you draw anything. Here you've a better answer: clear line on HTML5 Canvas
So the only way seems to use clearRect.
@danielfranca is right that a line drawn onto the canvas becomes "unremembered pixels in the canvas's sea of pixels."
He's also right that saving snapshot images of the canvas as each line is drawn and reverting to one of those saved images to "delete" a line is resource intensive. (Don't use that technique!!)
But, there is an efficient way to delete previously drawn lines on a canvas!
Yes, it does clear the canvas and redraw the lines, but it's very fast & efficient...I promise!
Here's an outline of how to do it:
Define a line inside an object like this:
{ x0:10, y0:15, x1:100, y1:75 }
Make as many of those lines as desired and push them into an array:
var lines=[];
Use the line definitions in the lines[] array to draw your lines onto the canvas.
Listen for
mousemove
andmousedown
events.On mousemove, iterate throught lines[] and find the line closest to the mouse. Here's a snippet of the algorithm that calculates which line is closest to a given [mx,my]:
On mousedown, use
lines.splice(targetIndex,1)
to remove the definition of the closest line from the lines[] array. Then clear the canvas and redraw the remaining lines.Here's annotated code and a Demo:
Maybe you would give a javascript drawing library a try. There is, for example the oCanvas library, where you draw more object oriented. There is a remove function which removes drawn objects from the canvas.