-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathtween.js
More file actions
61 lines (56 loc) · 1.4 KB
/
tween.js
File metadata and controls
61 lines (56 loc) · 1.4 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
function lerp(min,max,t) {
return min + (max-min)*t
}
class Tween {
constructor(group, cfg) {
this.group = group
this.target = cfg.target
this.property = cfg.property
this.from = cfg.from
this.to = cfg.to
this.duration = cfg.duration
this.started = false
this.ended = false
this.current = -1
this._onEnd = cfg.onEnd
}
tick(time) {
if(this.ended) return
if(!this.started) {
this.started = true
this.startTime = time
this.current = 0
}
this.current = (time-this.startTime)/this.duration
this.target[this.property] = lerp(this.from,this.to,this.current)
if(this.current >= 1) {
this.ended = true
this.target[this.property] = lerp(this.from,this.to,1)
if(this._onEnd) {
this._onEnd()
}
this.group.end(this)
}
}
onEnd(cb) {
this._onEnd = cb
return this
}
}
class TweenGroup {
constructor() {
this.active = []
}
tick(time) {
this.active.forEach(tween=>tween.tick(time))
}
make(cfg) {
const tween = new Tween(this,cfg)
this.active.push(tween)
return tween
}
end(tween) {
this.active = this.active.filter(t => t !== tween)
}
}
export const TWEEN = new TweenGroup()