簡體   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