Created
December 7, 2024 23:56
-
-
Save mindon/e4a01fd85a847adffac432d62c77dc65 to your computer and use it in GitHub Desktop.
Keep and restore css animation timepoint
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
// restore animation timepoint from first animation of an element | |
export function restore(anis, key) { | |
if (anis.length === 0) return; | |
const s = sessionStorage.getItem(key); | |
if (!s) return; | |
const t = s.split(",").map((v) => parseFloat(v)); | |
Array.from(anis).some((ani, i) => { | |
ani.pause(); | |
ani.startTime = t[0] || 0; | |
ani.currentTime = t[1] || 0; | |
ani.play(); | |
return false; | |
}); | |
} | |
// keep animation timepoint, only use first animation (disconnect and beforeunload) | |
export function save(anis, key, dur) { | |
if (!anis.length) return; | |
Array.from(anis).some((ani) => { | |
ani.pause(); | |
}); | |
const { effect, startTime, timeline } = anis[0]; | |
const at = effect.target; | |
if (!at) return; | |
const { currentTime } = timeline; | |
dur = dur || getComputedStyle(at).animationDuration; | |
sessionStorage.setItem( | |
key, | |
[ | |
(startTime || 0).toFixed(2), | |
((currentTime || 0) % | |
(parseInt(dur.replace("ms", "").replace("s", "000"), 10))) | |
.toFixed(2), | |
].join(","), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment