Javascript 在mousemove事件上跟踪画布x和y坐标动画
我试图用mousemove事件制作一个圆圈移动动画,每次圆圈都会从屏幕上的mouse.x和mouse.y坐标移动。所以我声明我的鼠标坐标对象和drawCricleobject构造函数:Javascript 在mousemove事件上跟踪画布x和y坐标动画,javascript,canvas,addeventlistener,Javascript,Canvas,Addeventlistener,我试图用mousemove事件制作一个圆圈移动动画,每次圆圈都会从屏幕上的mouse.x和mouse.y坐标移动。所以我声明我的鼠标坐标对象和drawCricleobject构造函数: var mouse = { x:canvas.width/2, y:canvas.height/2 } function Circle (x,y,r,dy){ this.x = x; this.y = y;
var mouse = {
x:canvas.width/2,
y:canvas.height/2
}
function Circle (x,y,r,dy){
this.x = x;
this.y = y;
this.r = r;
this.dy = dy;
this.update = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,Math.PI*2);
ctx.fillStyle = 'blue';
ctx.fill();
this.y+=this.dy;
if(this.y<this.r || this.y+this.r>canvas.height){
this.dy=-this.dy;
}
}
}
问题是mouse.xandmouse.yvalue不会从原始canvas.width/2value更改,因此我尝试将animationfunction包装在window.addEventListener中,而只是在其中调用它,就像:
window.addEventListener("mousemove",function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
var myCircle = new Circle(mouse.x,mouse.y,30,2);
function animate(){
ctx.clearRect(0,0,canvas.width,canvas.height);
myCircle.update();
requestAnimationFrame(animate);
}
animate();
});
这可能会有一点效果,但它看起来真的很愚蠢,使我的浏览器出现了巨大的滞后峰值,有没有其他方法可以做到这一点?在调用更新函数时,您还需要传递鼠标坐标 var canvas=document.querySelector'canvas'; var ctx=canvas.getContext'2d'; 变量鼠标={ x:canvas.width/2, y:canvas.height/2 }; 函数圈,y,r,dy{ 这个。r=r; this.dy=dy; this.update=functionx,y{ ctx.beginPath; ctx.arcx,y,this.r,0,Math.PI*2; ctx.fillStyle='蓝色'; ctx.fill; this.y+=this.dy; 如果this.y
我应该将this.update=functionthis.x,this.y{}添加到我的圆形对象中吗?或者在circle构造函数中声明x和y属性没有区别?不,这不起作用,因为您只创建了一次circle对象,但update函数被多次调用,因此需要显式传递这些坐标。在这种特殊情况下,在构造函数中声明这些内容和直接使用它们之间没有区别。
window.addEventListener("mousemove",function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
var myCircle = new Circle(mouse.x,mouse.y,30,2);
function animate(){
ctx.clearRect(0,0,canvas.width,canvas.height);
myCircle.update();
requestAnimationFrame(animate);
}
animate();
});