scrub animation
by Soviut
HTML
<div class="slide" id="anim">
testing
</div>
<input type="range" value="0" id="scrub">
CSS
.slide {
animation: slide 3s linear both;
}
@keyframes slide {
0% { transform: translateX(0); }
100% { transform: translateX(200px); }
}
JavaScript
const scrub = document.getElementById('scrub')
const anim = document.getElementById('anim')
anim.style.animationPlayState = 'paused'
animLength = 3000 // ms
scrub.max = animLength
let currentTime = 0
let lastTimestamp = null
scrub.addEventListener('input', (e) => {
update(parseInt(e.target.value, 10))
})
function update(time) {
anim.style.animationDelay = `-${time}ms`
scrub.value = time
}
function playback(timestamp) {
const delta = lastTimestamp !== null ? timestamp - lastTimestamp : 1
if (currentTime > animLength) {
currentTime = 0
}
currentTime += delta
update(currentTime)
lastTimestamp = timestamp
window.requestAnimationFrame(playback)
}
window.requestAnimationFrame(playback)