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
不,這不起作用,因爲您只創建一次圓對象一次,但更新函數被多次調用,因此您需要明確地傳遞這些座標。在這種特殊情況下,沒有差異。在構造函數中聲明並直接使用它們之間。 –