Animations

Usually, the cleanest way to perform animations is to apply CSS classes with atransitionproperty, or use CSS@keyframes. But if you need more flexibility (e.g. for a game), this can be done with JavaScript as well.

The naive approach would be to have awindow.setTimeout()function call itself until the desired animation is completed. However, this inefficiently forces rapid document reflows; and this_layout thrashing_can quickly lead to stuttering, expecially on mobile devices. Intead, we can sync the updates usingwindow.requestAnimationFrame()to schedule all current changes to the next browser repaint frame. It takes a callback as argument which receives the current (high res) timestamp:

const start = window.performance.now()
const duration = 2000

window.requestAnimationFrame(function fadeIn (now){
 const progress = now - start  
 myElement.style.opacity = progress / duration

 if(progress < duration){
    window.requestAnimationFrame(fadeIn)
    }
})

This way we can achieve very smooth animations. For a more detailed discussion, please have a look atthisarticle by Mark Brown.

results matching ""

    No results matching ""