2021SC@SDUSC
今天来看看时间线。时间线,其作用是用来计算元素上的某个属性在指定时间点上的数值,以便于动画的稳定有序播放,也便于处理动画过程中的操作。
首先是创建时间线。
function Timeline(options) {
_classCallCheck(this, Timeline);
this.element = options.element;
this.lifeTime = options.lifeTime || 1000;
this.delay = options.delay || 0;
this.loop = options.loop == null ? false : options.loop;
this.gap = options.gap || 0;
this.easing = options.easing || 'Linear';
this.onframe = options.onframe;
this.ondestroy = options.ondestroy;
this.onrestart = options.onrestart;
this._initialized = false;
this._pausedTime = 0;
this._paused = false;
}
这里是时间轴的构造,包括了时间轴的基本元素,时间轴的生命周期(默认值1000),时间轴的延迟,时间轴是否循环,时间线的空隙,时间轴的缓动,帧,时间线的销毁和重建。
_createClass(Timeline, [{
key: "nextFrame",
value: function nextFrame(globalTime, deltaTime) {
// Set startTime on first frame, or _startTime may has milleseconds different between clips
// PENDING
if (!this._initialized) {
this._startTime = globalTime + this.delay;
this._initialized = true;
}
if (this._paused) {
this._pausedTime += deltaTime;
return;
}
var percent = (globalTime - this._startTime - this._pausedTime) / this.lifeTime;
if (percent < 0) {
return;
}
percent = mathMin(percent, 1);
var easing = this.easing;
var easingFunc = typeof easing === 'string' ? easingFuncs[easing] : easing;
var schedule = typeof easingFunc === 'function' ? easingFunc(percent) : percent;
if (percent === 1) {
if (this.loop) {
this.restart(globalTime);
return 'restart';
}
return 'destroy';
} else {
this.fire('frame', schedule);
return percent;
}
}
这里的作用是进入下一帧,也就是时间线最主要的作用,是利用当前时间{Number} globalTime加时间偏移量{Number} deltaTime来实现。里面还包括了时间线初始化和暂停后重新开始的情况。当没有下一帧的时候,时间轴destory自动摧毁。
key: "restart",
value: function restart(globalTime) {
var remainder = (globalTime - this._startTime - this._pausedTime) % this.lifeTime;
this._startTime = globalTime - remainder + this.gap;
this._pausedTime = 0;
当重启动画的时候,利用原时间减开始时间减暂停时间和生命周期取余,获得重启时间轴位置。
key: "fire",
value: function fire(eventType, arg) {
eventType = 'on' + eventType;
if (this[eventType]) {
this[eventType](this.element, arg);
}
}
{
key: "pause",
value: function pause() {
this._paused = true;
}
{
key: "resume",
value: function resume() {
this._paused = false;
}
后面的开始暂停和恢复就大同小异没什么了