-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathparallax.coffee
76 lines (65 loc) · 2.09 KB
/
parallax.coffee
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
do (TweenMax, window, document) ->
class Parallax
# startingpoint must be 0
constructor: (@element, @keyframes) ->
do @compileTweens
Parallax::compileTweens = ->
@tweens = []
TweenMax.set @element, @keyframes[0].frame
for i in [[email protected]]
li = i - 1
dt = @keyframes[i].ratio - @keyframes[li].ratio
tween = TweenMax.to @element, dt, @keyframes[i].frame
tween.keyframe = @keyframes[i]
@tweens.push tween.pause()
Parallax::seek = (ratio) ->
# get ratio within range of 0~1
ratio = Math.max(ratio, 0)
ratio = Math.min(ratio, 1)
prevIndex = @index || @getIndex(@ratio)
currentIndex = @getIndex(ratio)
# forward
if !@ratio || @ratio < ratio
for i in [prevIndex...currentIndex]
tween = @tweens[i]
duration = tween.duration()
tween.seek(duration).pause()
# backward
else
for i in [prevIndex...currentIndex]
tween = @tweens[i]
tween.seek(0).pause()
# go to the position in the right tween
span = @getSpan(ratio)
@tweens[currentIndex].seek(span).pause()
# store ratio for comparison next time
@ratio = ratio
@index = currentIndex
Parallax::getSpan = (ratio) ->
# calculate the specific time of the current span of tween
span = ratio
currentTween = do =>
for tween in @tweens
_r = tween.keyframe.ratio
span -= tween.duration()
return tween if ratio <= _r
span += currentTween.duration()
Parallax::getIndex = (ratio) ->
index = 0
span = ratio
currentTween = do =>
for tween in @tweens
_r = tween.keyframe.ratio
span -= tween.duration()
return index if ratio <= _r
index++
# node export
if typeof module is 'object' && typeof module.exports is 'object'
module.exports = Parallax
# window export
else
window.Parallax = Parallax
# requirejs module definition
if typeof window.define is 'function' && window.define.amd
window.define 'parallax', [], ->
Parallax