2015-10-18 29 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;