【发布时间】:2022-11-16 14:04:35
【问题描述】:
我想用 convas 画线,但是当我尝试创建一条新线时,我以前的线被删除了。我第一次与 convas 打交道,如果你能告诉我我的错误和问题的解决方案,我会很高兴
const convas = document.querySelector(".v");
const ctx = convas.getContext("2d");
let startPositionLine = { x: 0, y: 0 };
let endPositionLine = { x: 0, y: 0 };
let { xStart, yStart } = startPositionLine;
let { xEnd, yEnd } = endPositionLine;
function moveMouseEvent(e) {
xEnd = e.offsetX;
yEnd = e.offsetY;
ctx.beginPath();
ctx.clearRect(0, 0, convas.width, convas.height);
ctx.moveTo(xStart, yStart);
ctx.lineTo(xEnd, yEnd);
ctx.stroke();
}
convas.onmousedown = (e) => {
ctx.beginPath();
xStart = e.offsetX;
yStart = e.offsetY;
ctx.stroke();
convas.onmousemove = (e) => moveMouseEvent(e);
};
convas.onmouseup = () => {
convas.onmousemove = null;
};
【问题讨论】:
-
您正在绘制
function moveMouseEvent那里有clearRect将清除所有内容 -
由于每次移动鼠标时都必须清除画布,因此您需要在绘制时将绘制的每条线的开始和结束 x 和 y 坐标保存到数组中。然后在
ctx.stroke();之后循环数组以重绘保存在数组中的每一行。因此,在数组中,每次单击画布时都会保存 Xstart、Ystart、xEnd、Yend。您还需要设置一个变量开关,以了解是否为每个单击/鼠标按下事件保存开始坐标或结束坐标。
标签: javascript canvas