forked from wesleytodd/transient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (53 loc) · 1.54 KB
/
index.js
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
var nextTick = require('browser-next-tick'),
noop = function(){};
var Transient = module.exports = function Transient(options) {
options = options || {};
// Animation settings
this.duration = options.duration || 5000;
this.fps = options.fps || 60;
this.loop = options.loop || false;
// Calculate total number of frames
this.frames = this.duration / 1000 * this.fps;
// Our callback functions
this.draw = options.draw || noop;
this.onEnd = options.onEnd || noop;
this.onCancel = options.onCancel || this.onEnd;
// Keep some internal state
this._canceled = false;
this._currentFrame = null;
this._startTime = null;
this._timeAcc = null;
};
Transient.prototype.start = function() {
var now = Date.now();
this._timeAcc = this._timeAcc || now;
this._startTime = now;
// For looped animations, compensate for lag between loops
if (this._timeAcc != this._startTime) {
this._timeAcc += this.duration;
this._startTime = this._timeAcc;
}
this.update();
};
Transient.prototype.update = function() {
// Did we cancel?
if (this._canceled) {
return this.onCancel();
}
var progress = (Date.now() - this._startTime) / this.duration;
// Are we done?
if (progress >= 1) {
return this.loop ? this.start() : this.onEnd();
}
// Determine frame
var frame = Math.floor(this.frames * progress);
if (frame !== this._currentFrame) {
this._currentFrame = frame;
this.draw(progress);
}
// Call again on next tick/request animation frame
nextTick(this.update.bind(this));
};
Transient.prototype.cancel = function() {
this._canceled = true;
};