Table of contents
JavaScript offers powerful capabilities for creating interactive and dynamic content on web pages. One popular use case is animating objects on an HTML canvas element. In this article, we'll explore how to create a simple ball animation using JavaScript and the HTML canvas element.
Getting Started
To begin, let's set up our HTML file with a canvas element where we'll draw our animation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ball Animation</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script>
// JavaScript code goes here
</script>
</body>
</html>
Drawing Balls on Canvas
Now, let's write the JavaScript code to draw balls on the canvas and animate them. We'll create a Ball class to represent each ball:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
class Ball {
constructor(x, y, dx, dy, radius, color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.color = color;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
update() {
// Move the ball
this.x += this.dx;
this.y += this.dy;
// Reverse direction if ball hits canvas boundaries
if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.dy = -this.dy;
}
}
}
// Create an array of balls
const balls = [];
for (let i = 0; i < 10; i++) {
const radius = Math.random() * 30 + 10;
const x = Math.random() * (canvas.width - 2 * radius) + radius;
const y = Math.random() * (canvas.height - 2 * radius) + radius;
const dx = (Math.random() - 0.5) * 4; // Random speed in x direction
const dy = (Math.random() - 0.5) * 4; // Random speed in y direction
const color = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`; // Random color
balls.push(new Ball(x, y, dx, dy, radius, color));
}
// Animation loop
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(ball => {
ball.update();
ball.draw();
});
}
animate();
Conclusion
In this tutorial, we've learned how to create a simple ball animation using JavaScript and the HTML canvas element. By defining a Ball class and animating its movement on the canvas, we can create engaging and interactive visual effects on web pages. Feel free to experiment with different parameters and add more features to customize your animation further!
If you have any questions or suggestions, feel free to leave a comment below. Don't forget to subscribe to our newsletter for more tutorials and updates on web development!