-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
43 lines (40 loc) · 1.31 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
import { easeInOutQuart } from './ease.js'
/**
* @callback tweenCallback
* @param {number} v - the current value of the tween
* @returns {void}
*/
/**
* change a number over time
* @arg {number} from - the number to start at
* @arg {number} to - the number to finish at
* @arg {tweenCallback} cb - function called as tween progresses
* @arg {object} [opts] - options
* @arg {number} [opts.time = 400] - how long the tween should last
* @arg {function} [opts.done] - function called when tweening is finished
* @arg {function} [opts.ease] - function used for easing the tween
* @returns {function} - callback that can stop a tween in progress
*/
export function tween(from, to, cb, { time = 400, done, ease = easeInOutQuart } = {}) {
const windowExists = (typeof window !== 'undefined')
let stopped = false
const stop = () => stopped = true
const diff = from - to
let start = null
function step(timestamp) {
if (stopped) return
if (!start) start = timestamp
const progress = timestamp - start
const percentage = Math.min(progress / time, 1)
cb(from - ease(percentage) * diff)
if (progress < time) {
window.requestAnimationFrame(step)
} else {
cb(to)
done && done()
}
}
windowExists && window.requestAnimationFrame(step)
return stop
}
export * from './ease.js'