Animation in JavaScript
JavaScript can be used to animate elements on a webpage. The setInterval() and requestAnimationFrame() methods are commonly used for animations.
Basic Animation Example
Here’s an example of how to animate a box across the screen using setInterval():
let box = document.getElementById("animateBox");
let position = 0;
let interval = setInterval(function() {
if (position < 300) {
position += 5;
box.style.left = position + "px";
} else {
clearInterval(interval);
}
}, 20);
Activity
Try It Yourself!
Animate an object on your webpage to move in any direction (up, down, left, right) using JavaScript.
Quiz
Quick Quiz
- What is the purpose of
setInterval()in JavaScript? - What is the advantage of using
requestAnimationFrame()? - What method would you use to stop an animation created by
setInterval()?
Answers: It repeatedly calls a function at specified intervals; it is more efficient for animations; clearInterval().