我在canvas(HTML5)中画了一个点。然后我想让这个点在一个圆形路径上动画。
我看到了一个使用时间差来设置x和y变量的示例,与时间有关。使用的一些变量和公式相当模糊,我已经忘记了我的物理知识。但是我已经对圆周运动进行了相当多的研究,所以我可以理解其中的一些内容。这是我的 codepen,展示了如何实现它。
基本上,这是我迄今为止确定的部分:
this.orbit = 100; // this is the radius of the circular orbit
this.radius = 5; // orbiting object's radius
this.velocity = 50; // yeah velocity but without direction, should be speed (agree?)
var angle = 0; starting angle of the point in the orbit inside the canvas's quadrant,
将x
和y
坐标设置为相对于画布坐标的位置。
首先通过将宽度和高度除以2来获取画布中心点
然后加上轨道半径与x
和y
相对于初始位置在轨道上的位置(angle)乘积,
由于Math三角函数使用弧度,因此我们应该将其乘以PI
和180
的商。
this.x = _width / 2 + this.orbit * Math.cos(angle * Math.PI / 180)
this.y = _height / 2 + this.orbit * Math.sin(angle * Math.PI / 180)
// by doing the above, we now get the initial position of x and y in the orbit.
对我来说相当琐碎的是下面这些变量:_dx
和_dy
,还有_magnitude
。
以下是点的动画方式:
Point.prototype.update = function(dt) {
var dps = this.orbit * 2 * Math.PI / this.velocity;
var angle = (360 / dps) * dt / 1000 * -1;
this.vx = this.vx * Math.cos(angle * Math.PI / 180) - this.vy*Math.sin(angle * Math.PI / 180);
this.vy = this.vx * Math.sin(angle * Math.PI / 180) + this.vy*Math.cos(angle * Math.PI / 180);
var _magnitude = Math.sqrt( this.vx * this.vx + this.vy * this.vy);
this.vx = this.vx / _magnitude * this.velocity;
this.vy = this.vy / _magnitude * this.velocity;
this.x += this.vx * dt / 1000;
this.y += this.vy * dt / 1000;
}
以下是脚本的执行结果:
function animate () {
dt = new Date() - ldt;
if (dt < 500) {
// context.clearRect(0, 0, canvas.width, canvas.height);
point.update(dt);
point.draw(context);
};
ldt = new Date();
setTimeout(function() {
window.requestAnimationFrame(animate);
}, 1000 / 30)
}
ldt = new Date();
animate();
对于像_dx _dy _magnitude
这样不清楚的变量,我无法理解它是如何工作和变量vx vy
的计算方式,我假设它们分别是相对于x和y的速度。
我想使用GreenSock TweenLite进行动画处理,方法如下:
Point.prototype.update = function(p){
var _to = {
x: , // change the value of x
y: , // change the value of y
ease: Cubic.easeInOut,
onComplete: function () { this.update(p) }
}
TweenLite.to(point, 2, _to)
}
正如您所看到的,第一个参数是当前对象(点),第二个参数是时间,我认为这是速度,第三个参数是对象属性x和y的变化。
问题
我创建了codepen,现在如何使用gsap tweenlite来像我所做的那样动画圆形,我想使用tweenlite会使它更简单一些。