FULL STACK   ·   UI   ·   UX   ·   GRAPHICS   ·   DEVELOPER   ·   INSTRUCTOR

Adam Khoury

Donate funds to show love and support

Click the button below to donate funds securely online. You can use your PayPal account or a credit card.

Your donations help free up my time to produce more content and assist in covering server costs. It's also a great way to say thanks for the content!

Application Configuration

Adam will be adding options here soon.

WAPG 4 Script Based Animation Programming JavaScript CSS Tutorial

Published :
Author :
Adam Khoury

Learn to program script-based animations with JavaScript using requestAnimationFrame, cancelAnimationFrame, setInterval or setTimeout. Using timing methods provides a greater level of control over how things animate on the screen and is ideal for video game development and other interactive animated applications. requestAnimationFrame is a method that invokes a callback function and uses the browser software's display refresh rate which is usually 60 Frames Per Second.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> #thing1 { position: absolute; top: 50px; background: #FC0; width: 50px; height: 50px; border-radius: 100%; } </style> </head> <body> <div id="thing1"></div> <button onmousedown="changeDir('left'); startAnimation()" onmouseup="stopAnimation()">Left</button> <button onmousedown="changeDir('right'); startAnimation()" onmouseup="stopAnimation()">Right</button> <script> var el = document.getElementById('thing1'); var reqID; var dir; function changeDir(d) { dir = d; } function startAnimation() { if( dir == "right" ) { el.style.left = (el.offsetLeft += 2) + 'px'; } else if( dir == "left" ) { el.style.left = (el.offsetLeft -= 2) + 'px'; } reqID = window.requestAnimationFrame(startAnimation); } function stopAnimation() { window.cancelAnimationFrame(reqID); } </script> </body> </html>