Created
September 16, 2020 17:01
-
-
Save dmail/d1d6528c93191adf0b2ab5fcdb892222 to your computer and use it in GitHub Desktop.
Animation in javascript
This file contains hidden or 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
document.querySelector('button').onclick = () => { | |
const scrollStart = document.querySelector(".menu-wrapper").scrollLeft | |
const scrollEnd = scrollStart + menuWrapperSize | |
startJavaScriptAnimation({ | |
duration: 300, | |
onProgress: ({ progress }) => { | |
document.querySelector(".menu-wrapper").scrollLeft = | |
scrollStart + (scrollEnd - scrollStart) * progress | |
}, | |
}) | |
} |
This file contains hidden or 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
export const startJavaScriptAnimation = ({ | |
duration = 300, | |
timingFunction = (t) => t, | |
onProgress = () => {}, | |
onCancel = () => {}, | |
onComplete = () => {}, | |
}) => { | |
if (isNaN(duration)) { | |
// console.warn(`duration must be a number, received ${duration}`) | |
return () => {} | |
} | |
duration = parseInt(duration, 10) | |
const startMs = performance.now() | |
let currentRequestAnimationFrameId | |
let done = false | |
let rawProgress = 0 | |
let progress = 0 | |
const handler = () => { | |
currentRequestAnimationFrameId = null | |
const nowMs = performance.now() | |
rawProgress = Math.min((nowMs - startMs) / duration, 1) | |
progress = timingFunction(rawProgress) | |
done = rawProgress === 1 | |
onProgress({ | |
done, | |
rawProgress, | |
progress, | |
}) | |
if (done) { | |
onComplete() | |
} else { | |
currentRequestAnimationFrameId = window.requestAnimationFrame(handler) | |
} | |
} | |
handler() | |
const stop = () => { | |
if (currentRequestAnimationFrameId) { | |
window.cancelAnimationFrame(currentRequestAnimationFrameId) | |
currentRequestAnimationFrameId = null | |
} | |
if (!done) { | |
done = true | |
onCancel({ | |
rawProgress, | |
progress, | |
}) | |
} | |
} | |
return stop | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment