【发布时间】:2015-02-14 14:06:22
【问题描述】:
我在画布 (html5) 中绘制了一个点。然后我想让这个点在圆形路径中动画。
我看到了一个使用时间差来设置 x 和 y 变量的示例,相对于时间。使用的一些变量和公式非常模糊,我忘记了我的物理,d * mn。但是我对圆周运动研究了很多,所以我可以理解其中的一些。这是我的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 的位置相加
关于轨道(角度)中的初始位置,并且由于数学三角
函数使用弧度,我们应该将它乘以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 会使它变得有点简单。
【问题讨论】:
-
您的问题到底是什么?您想了解脚本(codepen 链接)是如何工作的以及 greensock 动画的底层代码吗?
标签: javascript css html canvas gsap