问题描述
我有一个装有图像的画布。
现在,我想在图像的某些部分标记线条。
所以,我写了一些绘制的代码鼠标拖动一行。
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;
}
现在的问题是,拖动会创建一系列线条一个。
我试图在绘图之前保存上下文并在绘图后恢复它,但没有帮助。
注意,我无法使用clearRect()清除画布,因为我的图像数据将丢失。在这里,我使用了虚拟图像。
我创造了一个小提琴。
任何帮助将不胜感激。
问候,
Rohith
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
推荐答案
这篇关于在装有图像的画布上拖动鼠标拖动一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!