Last active
March 17, 2019 19:58
-
-
Save peeke/67cd617a206b36c0d0dff70681f53d8d to your computer and use it in GitHub Desktop.
Easily animate an arbitrary property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const noop = () => {} | |
const animate = function(options = {}) { | |
const defaultOptions = { from: 0, to: 1, duration: 1000, callback: noop, ease: t => t } | |
const { from, to, duration, callback, ease } = {...defaultOptions, ...options} | |
const delta = to - from | |
let start | |
return new Promise(resolve => { | |
const tick = time => { | |
if (!start) start = time | |
const progress = (time - start) / duration | |
if (progress >= 1) { | |
callback(to) | |
resolve() | |
return | |
} | |
callback(from + ease(progress * delta)) | |
window.requestAnimationFrame(tick) | |
} | |
window.requestAnimationFrame(tick) | |
}) | |
} | |
export default animate | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment