i want to draw a line element in html5
what i want to do is like this
mousedown event will be my starting position(x,y);
mousemove
when mouse is mouseup then it will be the end position..
i already done this part
what i want really is to see the line drawn in the canvas while i am moving the mouse when i already unpress the mouse the line will be drawn exactly in the canvas as it is previewed while the mouse is being move and press out
here is my code
canvas_draw.addEventListener('mousemove',function(e){
x=e.pageX-canvas_draw.offsetLeft;
y=e.pageY-canvas_draw.offsetTop;
},false);
canvas_draw.addEventListener('mousedown',function(e){
context_draw.beginPath();
context_draw.moveTo(x,y);
},false);
canvas_draw.addEventListener('mouseup',function(e){
context_draw.lineTo(x,y);
context_draw.stroke();
context_draw.closePath();
},false);
I guess that your intention is that the user sees a "preview" line in real-time which moves while the user moves the cursor, and your problem is that when you draw the line during the mousemove event, the line isn't erased when the cursor moves to a new position.
I see two approaches to solve this issue.
a) Create a backup copy of the canvas in the mousedown event by drawing it to a new, invisible canvas with drawImage()
. Before you draw the line in mousemove, draw the backup copy back to the real canvas to erase the line you drew in the previous mousemove event (you can improve the performance by only copying the part which was covered by the previous line).
b) Create a new, transparent canvas on top of the real canvas and use it for any user interface elements like the preview line. That way you can erase it at will without damaging the real canvas beneath it (keep in mind that most events will then be catched by the top canvas).