2017-06-03 71 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

不,这不起作用,因为您只创建一次圆对象一次,但更新函数被多次调用,因此您需要明确地传递这些坐标。在这种特殊情况下,没有差异。在构造函数中声明并直接使用它们之间。 –