我正在尝试使用HTML canvas编写代码,该代码将从发生mousemove事件的行开始创建一行。该线具有确定的方向,应继续延伸直到离开屏幕。我遇到的问题是,每当我移动鼠标时,都会有新行开始(这很好),但是前一行会停止扩展。我认为问题是因为每个新行都具有一组与前一行同名的参数,但是我不确定这是问题所在,也不知道如何解决。
这是我当前代码的jsfiddle:https://jsfiddle.net/tdammon/bf8xdyzL/
我开始创建一个名为mouse的对象,该对象带有x和y参数。 xbeg
和ybeg
将是我行的起始坐标。
let canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height= window.innerHeight;
let c = canvas.getContext('2d');
let mouse ={
x:undefined,
y:undefined,
}
window.addEventListener("mousemove",function(event){
mouse.x = event.x;
mouse.y = event.y;
xbeg = mouse.x;
ybeg = mouse.y;
})
接下来,我创建一个动画函数,该函数连续调用自身。我创建一个新的线对象,该对象将以
xbeg
和ybeg
参数为起点,并以xbeg+10
和ybeg+10
作为终点。然后该函数递增xbeg
和ybeg
。我希望此函数创建每当鼠标移动时都不会停止扩展的新行。function animate() {
requestAnimationFrame(animate);
new Line(xbeg,ybeg,xbeg+10,ybeg+10)
c.beginPath();
c.moveTo(xbeg,ybeg);
c.lineTo(xbeg+10,ybeg+10);
c.stroke();
xbeg += 1;
ybeg += 1;
}
最佳答案
我在您的代码中添加了所有行的数组:let linesRy = [];
,并通过添加this.endx++; this.endy++;
更改了draw()函数
我也在用您注释掉的c.clearRect(0, 0, innerWidth, innerHeight);
,因为每一帧都重画了所有线条。
我希望这是您所需要的。
let linesRy = [];
let canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let c = canvas.getContext("2d");
let mouse = {
x: undefined,
y: undefined
};
let xbeg, ybeg;
window.addEventListener("mousemove", function(event) {
mouse.x = event.x;
mouse.y = event.y;
xbeg = mouse.x;
ybeg = mouse.y;
});
class Line {
constructor(begx, begy, endx, endy, dx, dy, slope) {
this.begx = begx;
this.begy = begy;
this.endx = endx;
this.endy = endy;
this.dx = endx - begx;
this.dy = endy - begy;
this.slope = dy / dx;
}
draw() {
this.endx++;
this.endy++;
c.beginPath();
c.moveTo(this.begx, this.begy);
c.lineTo(this.endx, this.endy);
c.stroke();
}
}
//let xend = 420;
//let yend = 220;
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, innerWidth, innerHeight);
linesRy.push(new Line(xbeg, ybeg, xbeg + 10, ybeg + 10, 10, 10, 1));
linesRy.forEach(l => {
l.draw();
});
}
animate();
canvas{border:1px solid;}
<canvas></canvas>
关于javascript - HTML Canvas使用mouseover事件制作线条,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52694204/