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

问题描述 投票:0回答:1

我试图用mousemove事件制作一个圆圈移动动画,每次圆圈将从我的mouse.xmouse.ycoordinates移动到屏幕上。所以我声明我的mouse坐标对象和drawCricleobject构造函数:

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

然后我添加了mousemoveevent所以我想我可以通过我的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.xandmouse.yvalue不会改变原来的canvas.width/2value,所以我试图在animation()中包装我的window.addEventListenerfunction而不是只是在内部调用它,就像:

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

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

javascript canvas addeventlistener
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.