Javascript 从任意位置将画布形状设置为中心动画
因此,我有点困惑,我如何才能使一个形状的动画画布的中心。我可以得到中心值:Javascript 从任意位置将画布形状设置为中心动画,javascript,html,canvas,Javascript,Html,Canvas,因此,我有点困惑,我如何才能使一个形状的动画画布的中心。我可以得到中心值: width = canvas.width = window.innerWidth, height = canvas.height = window.innerHeight, centerX = width / 2, centerY = height / 2; 根据初始位置是正还是负,也可以进行简单的递减或递增: var x = 100; var y = 100; function fn (){
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 = 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;
我有一辆新的JSFIDLE。我也在正确的轨道上吗?我明白了,我以前从未使用过sqrt,我一直想知道为什么要在allI使用它。我可能需要一些帮助来了解距离部分是如何工作的。例如,为什么要用tx乘以tx等等,我们基本上是用毕达哥拉斯法则来计算两点之间的距离。只是对答案的一个快速警告。当到达中心时,解决方案很有可能崩溃。在这种情况下,解决方案是将向量tx,ty向中心归一化(normalize是将向量设置为一个单位长),如果到中心的距离为零,您将得到一个被零除的错误,该错误将停止代码。。在对向量进行归一化时,始终检查是否未被零除。
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;