-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtween.js
More file actions
100 lines (82 loc) · 1.95 KB
/
tween.js
File metadata and controls
100 lines (82 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var ease = require('./ease');
var Emitter = require('./emitter');
function extend(obj, src) {
for (var key in src) {
if (src.hasOwnProperty(key)) obj[key] = src[key];
}
return obj;
}
function Tween(obj) {
if (!(this instanceof Tween)) return new Tween(obj);
this._from = obj;
this.ease('linear');
this.duration(500);
}
Emitter(Tween.prototype);
Tween.prototype.reset = function(){
this.isArray = Object.prototype.toString.call(this._from) === '[object Array]';
this._curr = extend({}, this._from);
this._done = false;
this._start = Date.now();
return this;
};
Tween.prototype.to = function(obj){
this.reset();
this._to = obj;
return this;
};
Tween.prototype.duration = function(ms){
this._duration = ms;
return this;
};
Tween.prototype.ease = function(fn){
fn = 'function' == typeof fn ? fn : ease[fn];
if (!fn) throw new TypeError('invalid easing function');
this._ease = fn;
return this;
};
Tween.prototype.stop = function(){
this.stopped = true;
this._done = true;
this.emit('stop');
this.emit('end');
return this;
};
Tween.prototype.step = function(){
if (this._done) return;
var duration = this._duration;
var now = Date.now();
var delta = now - this._start;
var done = delta >= duration;
if (done) {
this._from = this._to;
this._update(this._to);
this._done = true;
this.emit('end');
return this;
}
var from = this._from;
var to = this._to;
var curr = this._curr;
var fn = this._ease;
var p = (now - this._start) / duration;
var n = fn(p);
if (this.isArray) {
for (var i = 0; i < from.length; ++i) {
curr[i] = from[i] + (to[i] - from[i]) * n;
}
this._update(curr);
return this;
}
for (var k in from) {
curr[k] = from[k] + (to[k] - from[k]) * n;
}
this._update(curr);
return this;
};
Tween.prototype.update = function(fn){
if (0 == arguments.length) return this.step();
this._update = fn;
return this;
};
module.exports = Tween;