在mousemove事件中跟踪画布x和y坐标动画

时间:2017-06-03 16:49:49

标签: javascript canvas addeventlistener

我正在尝试使用mousemove事件创建一个圆圈移动动画,每次圆圈将从屏幕上的mouse.xmouse.y坐标移动。所以我声明我的mouse坐标对象和drawCricle对象构造函数:

    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事件后,我想我可以通过我的mouvemove eventListenter分配鼠标x / y坐标:

    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值更改,因此我尝试将animation()函数包装在{window.addEventListener内1}}而只是在其中调用它,就像:

    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();
    });

这可能会有点工作,但它看起来真的很愚蠢,并使我的浏览器出现巨大的滞后峰值,有没有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分: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>