Animation in Canvas
HTML5 Canvas makes it easy to create smooth and dynamic animations using JavaScript. By redrawing shapes continuously at updated positions, we can simulate movement.
How Canvas Animation Works
Canvas animation is done by:
Example: Moving Rectangle
Canvas animation is done by:
- Clearing the canvas.
- Updating the position of objects.
- Redrawing them in the new location.
- Repeating this using requestAnimationFrame().
Example: Moving Rectangle
Let us create an animation of a green rectangle moving from left to right:
What's Happening Behind the Scenes ?
Output:
<canvas id="myCanvas" width="500" height="400"></canvas><script> const canvas = document.getElementById('myCanvas'); const context = canvas.getContext('2d'); let x = 0;
function draw() { context.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas context.fillStyle = 'green'; context.fillRect(x, 50, 50, 50); // Draw rectangle x += 2; // Move it 2px to the right requestAnimationFrame(draw); // Keep the loop going }
draw(); // Start the animation</script>
What's Happening Behind the Scenes ?
Step | Description |
---|---|
clearRect() | Clears the canvas to prevent drawing over the previous frame. |
fillRect(x, 50, 50, 50) | Draws a green rectangle at the new x position. |
x +=2 | Moves the rectangle 2 pixels to the right. |
requestAnimationFrame(draw) | Crates a smooth animation loop at ~60fps. |
Output:
A green square smoothly moves across the canvas from left to right. Once it reaches the edge, it keeps moving off-screen unless you add logic to reset or bounce it.
Why Use requestAnimationFrame()?
- Efficient: Optimized for smooth frame rates.
- Syncs with screen refresh rate.
- Reduces CPU usage compared to setInterval().