Skip to content

Instantly share code, notes, and snippets.

@csenio
Last active March 14, 2020 16:44
Show Gist options
  • Save csenio/097cc51851a56b01b8df0d374067ef1a to your computer and use it in GitHub Desktop.
Save csenio/097cc51851a56b01b8df0d374067ef1a to your computer and use it in GitHub Desktop.
a basic tweening function, where the value is updated via cb. adjusted for perfect 60fps movement
const _raf =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(f) {
window.setTimeout(f, 1e3 / 60);
};
const getTime = typeof performance === "function" ? performance.now : Date.now;
const tween = ({ cb, duration, from, to, onComplete = () => {}, paused }) => {
const animation = {
lastUpdate: getTime(),
_frameDuration: 1000 / 60,
value: 0
};
// make value transition between a and b in x time
function interpolatedCb(val) {
const percentage = val / duration;
const distance = to - from;
const value = percentage * distance + from;
return cb(value);
}
// normalized frame loop, value always changes at 60fps
function animate() {
const now = getTime();
// how much time has passed since the last update -> ensure 60fps for precise durations
const delta = (now - animation.lastUpdate) / animation._frameDuration;
animation.value += delta;
animation.lastUpdate = now;
interpolatedCb((animation.value * 1000) / 60);
console.log(paused);
if (paused) {
return;
}
if (duration && (animation.value * 1000) / 60 <= duration) {
_raf(animate);
} else {
onComplete();
}
}
animate();
};
export default tween;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment