Animations in JavaScript¶
There are several ways to create animations, but I’ll explain a simple method using the requestAnimationFrame function.
The requestAnimationFrame method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. Here’s a basic example:
let start;
function step(timestamp) {
if (start === undefined)
start = timestamp;
const elapsed = timestamp - start;
// Your animation code here
if (elapsed < 2000) { // Stop the animation after 2 seconds
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
In this example, step is the function that contains the animation code. It’s called repeatedly by requestAnimationFrame until the animation is complete.
Here’s an example of how you might use this to animate an element:
let start;
let element = document.getElementById('myElement');
function step(timestamp) {
if (start === undefined)
start = timestamp;
const elapsed = timestamp - start;
// Move the element to the right by 1px every millisecond
element.style.transform = 'translateX(' + elapsed * 0.001 + 'px)';
if (elapsed < 2000) { // Stop the animation after 2 seconds
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
In this example, the element with the ID ‘myElement’ will move to the right by 1px every millisecond, for a total of 2 seconds.
Remember, animations can be complex and may require a good understanding of timing and easing functions. For complex animations, you might want to consider using a JavaScript animation library like anime.js, greensock (GSAP), or velocity.js.