Hosting Solutions
mobile_logo Table of Contents
seal_frontseal_back

WAPG 4 Script Based Animation Programming JavaScript CSS Tutorial

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>
thumb

JavaScript Videos

Web Animation Programming Guide

WAPG 1 Transition Animation Programming CSS JavaScriptWAPG 2 keyframes Animation Programming CSS JavaScriptWAPG 3 Sprite Animation Programming CSS JavaScriptWAPG 4 Script Based Animation Programming JavaScript CSS TutorialWAPG 5 Collision Hit Detection DOM Programming JavaScript TutorialWAPG 6 SVG Animation Programming SMIL JavaScript CSS