Created
August 20, 2017 10:07
-
-
Save JoostKiens/713177fdcf0e52a71a545e24e83f79f3 to your computer and use it in GitHub Desktop.
Transition numbers over time with easing
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
/* | |
Options | |
--- | |
{ | |
from: 1, // <Number> start number, default: 0 | |
to: 100, // <Number> end number, required | |
duration: 1000, // <Number> total duration on transition, required | |
step: console.log, // <Function> function to execute on each update, receives current number as argument, required | |
ease: x => x, // <Function> custom easing function, default: linear | |
tick: fn => window.setTimeout(fn, 20) // <Function> ticker, default: requestAnimationFrame | |
} | |
Example usage | |
--- | |
function handleStep (x) { | |
console.log(Math.round(x).toLocaleString()) | |
} | |
function easeInCubic (t) { | |
return t * t * t | |
} | |
function tick (fn) { | |
window.setTimeout(fn, 20) | |
} | |
numberTransition({ from: 1, to: 5000, duration: 1000, step: handleStep, ease: easeInCubic, tick }) | |
*/ | |
export default function numberTransition({ from = 0, to, ease = linear, tick = raf, ...rest }) { | |
tick(() => next({ startTime: new Date(), delta: to - from, from, ease, tick, ...rest })) | |
} | |
function next(args) { | |
const { startTime, delta, from, ease, duration, step, tick } = args | |
const elapsed = new Date() - startTime | |
const factor = Math.min(elapsed / duration, 1) | |
step(from + delta * ease(factor)) | |
if (factor !== 1) { | |
tick(() => next(args)) | |
} | |
} | |
function linear (x) { | |
return x | |
} | |
function raf (fn) { | |
window.requestAnimationFrame(fn) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment