我正在尝试使用HTML画布编写代码,该代码将在发生mousemove事件的地方开始创建一行。该线具有确定的方向,应继续延伸直到离开屏幕。我遇到的问题是,每当我移动鼠标时,都会有新行开始(这很好),但是前一行会停止扩展。我认为该问题是因为每个新行都具有一组与上一行相同名称的参数,但是我不确定这是问题所在,也不知道如何解决。
这是我当前代码的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;
}
答案 0 :(得分:3)
我已将所有行的数组添加到您的代码中:let linesRy = [];
,并通过添加this.endx++; this.endy++;
我还要使用您注释掉的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>
答案 1 :(得分:-1)
变量c为局部变量
function animate() {
c = canvas.getContext('2d');
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;
}