0
嗨,我想用mousemove
事件做一个圆形移动动画,每次圆形将从我的mouse.x
和mouse.y
坐标移动到屏幕上。所以我宣布我的mouse
坐标对象和drawCricle
对象的构造函数:跟踪画布x和y坐标在mousmove事件上的动画
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;
}
}
}
后,我加入mousemove
事件,所以我想我可以将鼠标的x/y通过坐标我mouvemove eventListenter
:
var myCircle = new Circle(mouse.x,mouse.y,30,2);
function animate(){
ctx.clearRect(0,0,canvas.width,canvas.height);
myCircle.update();
requestAnimationFrame(animate);
}
window.addEventListener("mousemove",function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
animate();
});
问题是mouse.x
和mouse.y
的值不会从原来的canvas.width/2
值中改变,所以我试图在window.addEventListener
内部封装我的animation()
函数,而不是仅仅调用它,就像:
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();
});
这可能是工作有点,但它看起来很愚蠢,使我的自带浏览器巨大的laggy尖峰,是否有任何其他方式做到这一点?
我应该添加this.update =功能(this.x,this.y) {}在我的圈子对象内?或者在circle构造函数中声明x和y属性没有区别? – mystreie
不,这不起作用,因为您只创建一次圆对象一次,但更新函数被多次调用,因此您需要明确地传递这些坐标。在这种特殊情况下,没有差异。在构造函数中声明并直接使用它们之间。 –