2017-06-03 69 views
0

嗨,我想用mousemove事件做一個圓形移動動畫,每次圓形將從我的mouse.xmouse.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.xmouse.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尖峯,是否有任何其他方式做到這一點?

回答

1

您還需要通過調用update功能,當鼠標的座標...

var canvas = document.querySelector('canvas'); 
 
var ctx = canvas.getContext('2d'); 
 
var mouse = { 
 
    x: canvas.width/2, 
 
    y: canvas.height/2 
 
}; 
 

 
function Circle(x, y, r, dy) { 
 
    this.r = r; 
 
    this.dy = dy; 
 
    this.update = function(x, y) { 
 
     ctx.beginPath(); 
 
     ctx.arc(x, 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; 
 
     } 
 
    }; 
 
} 
 

 
var myCircle = new Circle(mouse.x, mouse.y, 30, 2); 
 

 
function animate() { 
 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
 
    myCircle.update(mouse.x, mouse.y); 
 
    requestAnimationFrame(animate); 
 
} 
 

 
canvas.addEventListener("mousemove", function(e) { 
 
    mouse.x = e.offsetX; 
 
    mouse.y = e.offsetY; 
 
}); 
 

 
animate();
body{margin:10px 0 0 0;overflow:hidden}canvas{border:1px solid #e4e6e8}
<canvas id="canvas" width="635" height="208"></canvas>

+0

我應該添加this.update =功能(this.x,this.y) {}在我的圈子對象內?或者在circle構造函數中聲明x和y屬性沒有區別? – mystreie

+0

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