Last active
June 3, 2021 11:51
-
-
Save anish000kumar/2ca0ec7de78502a04790e2cb83dc74f0 to your computer and use it in GitHub Desktop.
Animation loop
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
function animate({ timing, duration, draw }){ | |
return new Promise((resolve, reject) => { | |
const start = performance.now(); | |
function animation(time){ | |
const progress = Math.min((time-start)/duration, 1); | |
const visualProgress = timing ? timing(progress): progress; | |
draw(visualProgress); | |
if(progress < 1) requestAnimationFrame(animation) | |
else resolve() | |
} | |
requestAnimationFrame(animation) | |
}) | |
} | |
// USAGE examples | |
const el = document.getElementsByTagName('div')[0] | |
const toRight = { | |
duration: 1000, | |
draw(progress){ | |
el.style.transform = `translateX(${300*progress}px)` | |
} | |
}; | |
const toLeft = { | |
duration: 1000, | |
draw(progress){ | |
el.style.transform = `translateX(${300 - 300*progress}px)` | |
} | |
}; | |
animate(toRight) | |
.then(() => animate(toLeft)) | |
.then(() => animate(toRight)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment