13
HTML5 <canvas> provides a powerful way to create dynamic, interactive animations using JavaScript. In this tutorial, you’ll learn the basics of animating objects, combining movements, and creating visually appealing effects.
What You’ll Learn
- The core concepts of canvas animation.
- Moving objects with the animation loop.
- Creating smooth transitions using requestAnimationFrame.
- Combining movements and adding interactivity.
- Practical animation examples.
1. Basics of Canvas Animations
Canvas animations involve:
- Clearing the canvas: To redraw the frame.
- Drawing objects: Define what needs to be animated.
- Updating object properties: Adjust the position, size, or other attributes.
- Repeating the process: Use requestAnimationFrame to create the animation loop.
2. Setting Up the Canvas
Example 1: Setting Up the Canvas
<canvas id="myCanvas" width="500" height="300" style="border: 1px solid black;"></canvas> <script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); </script>
3. Creating a Moving Object
Example 2: Moving a Circle Horizontally
let x = 0; // Initial x-coordinate const radius = 20; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas // Draw the circle ctx.beginPath(); ctx.arc(x, canvas.height / 2, radius, 0, Math.PI * 2); ctx.fillStyle = "blue"; ctx.fill(); ctx.closePath(); // Update the position x += 2; if (x - radius > canvas.width) { x = -radius; // Reset when off-screen } requestAnimationFrame(draw); // Repeat the animation } draw();
Explanation:
- clearRect: Clears the canvas before each frame.
- requestAnimationFrame: Schedules the next frame for smooth animation.
4. Adding Vertical Movement
You can add vertical movement by updating the Y-coordinate.
Example 3: Bouncing Ball
let x = 100; let y = 50; let dx = 2; // Change in x let dy = 2; // Change in y const radius = 20; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw the ball ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI * 2); ctx.fillStyle = "red"; ctx.fill(); ctx.closePath(); // Update position x += dx; y += dy; // Bounce off walls if (x + radius > canvas.width || x - radius < 0) { dx = -dx; // Reverse direction } if (y + radius > canvas.height || y - radius < 0) { dy = -dy; // Reverse direction } requestAnimationFrame(draw); } draw();
5. Animating Multiple Objects
Example 4: Moving Multiple Balls
const balls = [ { x: 50, y: 60, dx: 2, dy: 1, color: "blue" }, { x: 200, y: 100, dx: -1.5, dy: 2, color: "green" }, { x: 300, y: 50, dx: 2, dy: -2, color: "orange" } ]; function drawBalls() { ctx.clearRect(0, 0, canvas.width, canvas.height); balls.forEach((ball) => { // Draw each ball ctx.beginPath(); ctx.arc(ball.x, ball.y, radius, 0, Math.PI * 2); ctx.fillStyle = ball.color; ctx.fill(); ctx.closePath(); // Update position ball.x += ball.dx; ball.y += ball.dy; // Bounce off walls if (ball.x + radius > canvas.width || ball.x - radius < 0) { ball.dx = -ball.dx; } if (ball.y + radius > canvas.height || ball.y - radius < 0) { ball.dy = -ball.dy; } }); requestAnimationFrame(drawBalls); } drawBalls();
6. Adding Easing and Smooth Transitions
Example 5: Easing Animation
let targetX = 400; // Target position let x = 0; // Current position function easeAnimation() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw the object ctx.beginPath(); ctx.arc(x, canvas.height / 2, radius, 0, Math.PI * 2); ctx.fillStyle = "purple"; ctx.fill(); ctx.closePath(); // Update position (easing) x += (targetX - x) * 0.05; // Move closer to the target requestAnimationFrame(easeAnimation); } easeAnimation();
Explanation:
- The easing formula x += (targetX – x) * 0.05 creates a smooth transition by reducing the distance incrementally.
7. Adding Interactivity
Example 6: Interactive Animation (Follow Mouse)
let mouseX = 0; let mouseY = 0; canvas.addEventListener("mousemove", (event) => { const rect = canvas.getBoundingClientRect(); mouseX = event.clientX - rect.left; mouseY = event.clientY - rect.top; }); function followMouse() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw a circle at the mouse position ctx.beginPath(); ctx.arc(mouseX, mouseY, radius, 0, Math.PI * 2); ctx.fillStyle = "orange"; ctx.fill(); ctx.closePath(); requestAnimationFrame(followMouse); } followMouse();
8. Practical Example: Animated Scene
Example 7: A Simple Solar System
let angle = 0; function drawSolarSystem() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw the sun ctx.beginPath(); ctx.arc(250, 150, 30, 0, Math.PI * 2); ctx.fillStyle = "yellow"; ctx.fill(); ctx.closePath(); // Draw the earth orbit const earthX = 250 + Math.cos(angle) * 100; const earthY = 150 + Math.sin(angle) * 100; ctx.beginPath(); ctx.arc(earthX, earthY, 15, 0, Math.PI * 2); ctx.fillStyle = "blue"; ctx.fill(); ctx.closePath(); // Draw the moon orbiting the earth const moonX = earthX + Math.cos(angle * 4) * 30; const moonY = earthY + Math.sin(angle * 4) * 30; ctx.beginPath(); ctx.arc(moonX, moonY, 5, 0, Math.PI * 2); ctx.fillStyle = "gray"; ctx.fill(); ctx.closePath(); angle += 0.02; // Adjust speed requestAnimationFrame(drawSolarSystem); } drawSolarSystem();
9. Best Practices for Canvas Animations
- Use requestAnimationFrame:
- Provides smoother animations and optimizes performance.
- Keep It Clean:
- Always clear the canvas before redrawing.
- Isolate Logic:
- Use separate functions for drawing, updating, and handling user input.
- Optimize Performance:
- Minimize unnecessary calculations during each frame.
10. Browser Support
All modern browsers support canvas animations:
Feature | Supported? |
---|---|
requestAnimationFrame | Yes |
Canvas Drawing API | Yes |
11. Conclusion
In this tutorial, you learned:
- The basics of creating animations with HTML5 Canvas.
- How to move, resize, and rotate objects dynamically.
- How to create interactive animations and combine movements.