Click here to Skip to main content
15,076,465 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I have a canvas loaded with an image.
Now, I want to mark lines on some part of the image.
So, I wrote some code which draws a line on mouse drag.

JavaScript
function drawLine(x, y) {
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(x, y);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
}

canvas.onmousedown = function (e)  {
    ctx.save();
    e.preventDefault();
    e.stopPropagation();
    startX = parseInt(e.clientX - offsetX);
    startY = parseInt(e.clientY - offsetY);
    isDown = true;
}
canvas.onmousemove = function (e)  {
    if (!isDown) {
        return;
    }
    e.preventDefault();
    e.stopPropagation();
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);
    drawLine(mouseX, mouseY);
}
canvas.onmouseup = function (e)  {
    if (!isDown) {
        return;
    }
    e.preventDefault();
    e.stopPropagation();
    isDown = false;
}



The issue now is that, the drag creates a series of lines instead of one.
I have tried to save the context before drawing and restore it after drawing, but didn't help.

Note that, I cannot clear the canvas using clearRect(), as my image data will be lost. Here, I have using a dummy image.

I have created a fiddle. link

Any help would be appreciated.

Regards,
Rohith
Posted
Comments
vyas_pratik20 13-May-14 8:19am
   
hi Rohit,

you don't want to clear your out put then you have to use code like this :
[^]

this will not draw line on mouse up instead of down
Rohith M 14-May-14 4:09am
   
Thanks for the help, but I want to see what I am drawing.
That means, with mouse drag, the line should be updated.
Rohith M 14-May-14 4:22am
   
Thanks, I got the solution here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900