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.
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