繁体   English   中英

动画画布形状以从任何位置居中

[英]Animating canvas shape to center from any position

因此,我对如何使形状动画到画布中心感到有些困惑。 我可以得到中心值:

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值随形状随机变化,使其无论朝向哪个方向,以及初始位置是正还是负,都使其对中心具有动画效果。 我当时在想atang2,但说实话我不确定。

您基本上是在正确的轨道上。 使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM