将画布形状从任何位置动画到中心
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值随机,并使其动画到中心,无论从哪个方向,无论初始位置是负的还是正的。
你基本上在正确的轨道上。用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;
相关文章:
- jquery:将动画绑定到滚动条位置的更好方法
- Famo.us Js-将实体(粒子)设置到位置的动画
- 在位置更改时为阵列项目制作动画
- 仅为背景位置X轴制作动画
- 如何使用jQuery对固定元素的位置进行动画处理
- 是否可以设置柔盒插入、移除和项目位置的动画
- 如何获取SVG动画的当前时间/位置
- 在变换的绝对位置发生变化时制作动画's参数
- 如何使用CSS-webkit动画制作位置动画
- 视差'背景图像/位置/附件'jQuery的动画很不稳定
- 创建从一个位置到另一个位置的路径动画
- 在单击位置显示动画
- 如何将开始和结束位置应用于jquery视差动画
- 如果页面已在目标位置,则停止动画
- JavaScript动画位置问题
- 对象动画-位置更新失败
- jQuery动画位置不工作
- jQuery鼠标在菜单和动画位置元素后面
- 动画位置时,使用js不工作,我需要使用什么
- Jquery动画位置不适用于页边空白顶部