2015-10-18 85 views
0

所以我有點困惑我怎樣才能使一個形狀動畫的畫布中心。我能得到的中心值:動畫畫布形狀從任何位置居中

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,但是老實說我不完全確定。

回答

2

你基本上是在正確的軌道上。距離使用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; 
} 
+0

我有一個新的jsfiddle。我是否也在正確的軌道上? http://jsfiddle.net/4zmnrwzj/2/ – Asperger

+0

我明白了,我以前從未使用過sqrt,總是想知道爲什麼要使用它。 – Asperger

+0

我需要一些幫助來理解距離部分的工作原理。例如,爲什麼乘tx等tx等 – Asperger

0

給出的答案是有缺陷的,因爲沒有檢查除以零。這個錯誤很容易被忽略,然後在生產代碼中出現,很難找出錯誤。

應該

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;