â ī¸ Warning â ī¸ Deprecated Code! This video tutorial contains outdated code.
đĄ If you wish to update it, any AI assistant will update the code for you in seconds.
đĄ If you wish to update it, any AI assistant will update the code for you in seconds.
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>