将画布形状从任何位置动画到中心

Animating canvas shape to center from any position

本文关键字:动画 位置 任何 布形状      更新时间:2023-09-26

所以我对如何使形状动画到画布的中心有点困惑。我可以得到中间的值:

width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight,
centerX = width / 2,
centerY = height / 2;

和一个简单的递减或递增取决于初始位置是正还是负也可以做到:

var x = 100;
var y = 100;
    function fn (){
       ctx.beginPath();
       ctx.arc(x, y, 50, 0, 2 * Math.PI, false);
       ctx.fillStyle = '#444';
       ctx.fill();
       ctx.closePath();
       x -= 1;
       y -= 1;
    }

动画将使用:

requestAnimationFrame(fn)

这一切的问题是。我需要每次手动调整x和y。我如何才能更好地让形状的x和y值随机,并使其动画到中心,无论从哪个方向,无论初始位置是负的还是正的。

你基本上在正确的轨道上。用Math.sqrt表示距离,用Math.atan2表示方向。接下来的问题就是你希望物体移动到目标(画布中心)的速度有多快。

var tx = centerX - x,
    tx = centerY - y,
    distance = Math.sqrt(tx * tx + ty * ty),
    radius = Math.atan2(ty, tx),
    angle = (radius / Math.PI) * 180;
// Ensure we don't divide by zero if distance is 0
if (distance !== 0)
{
   velX = (tx / distance) * velocity;
   velY = (ty / distance) * velocity;
   x += velX;
   y += velY;
}

给出的答案是有缺陷的,因为没有检查除以零。这个错误很容易被忽略,然后在产品代码中突然出现,这使得很难发现哪里出了问题。

应该

var tx = centre.x - x;
var ty = centre.y - y;
var dist = Math.sqrt(tx * tx + ty * ty);
// or 
var dist = Math.sqrt(Math.pow(tx, 2) + Math.pow(ty, 2));
if(dist !== 0){ // must have this test or when the coords get to the centre 
                // you will get a divide by zero
     tx /= dist;  // Normalise direction vector
     ty /= dist;
}
tx *= speed; // set the magnitude to required speed;
ty *= speed; // Note that if at the centre this will be zero
x += tx;
y += ty;