The Bouncing Ball: A Mesmerizing HTML5 Canvas Animation
In this blog post, we'll explore how to create a captivating bouncing ball animation using the power of HTML5 canvas and native JavaScript APIs. By harnessing the canvas element and its drawing methods, we'll bring a simple ball to life, making it bounce around the screen mesmerizingly.
The Canvas
Create an HTML file and add a canvas element to it:
<!DOCTYPE html>
<html>
<head>
<title>Bouncing Ball</title>
</head>
<body>
<canvas id="mojoCanvas" width="500" height="500"></canvas>
<script src="script.js"></script>
</body>
</html>
We have a 500 x 500 canvas ready for you!
The Script JS
// Get the canvas element
const canvas = document.getElementById('mojoCanvas');
const ctx = canvas.getContext('2d');
// Set the ball's initial position and velocity
let x = canvas.width / 2;
let y = canvas.height / 2;
let radius = 20;
let dx = 2;
let dy = 2;
// Define the game loop
function drawBall() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the ball
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
// Update the ball's position
x += dx;
y += dy;
// Check for collisions with the walls
if (x + dx > canvas.width - radius || x + dx < radius) {
dx = -dx;
}
if (y + dy > canvas.height - radius || y + dy < radius) {
dy = -dy;
}
// Request the next frame
requestAnimationFrame(drawBall);
}
// Start the game loop
drawBall();
Understanding the code:
We get the canvas element using
document.getElementById('mojoCanvas')
and create a 2D rendering context usinggetContext('2d')
.We set the ball's initial position (
x
,y
), radius (radius
), and velocity (dx
,dy
).The function
drawBall
() is the main game loop:It clears the canvas using
clearRect()
.It draws the ball using
beginPath()
,arc()
,fillStyle
, andfill()
.It updates the ball's position by adding the velocity to the position.
It checks for collisions with the walls and reverses the velocity if necessary.
It recursively calls itself using
requestAnimationFrame()
to create the animation loop.
Finally, we start the game loop by calling
drawBall()
.
Styling the Page
To make the page more visually appealing, let's add some CSS to index.html
:
<style>
body {
margin: 0;
padding: 0;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
border: 1px solid #000;
background-color: #fff;
}
</style>
Okay now enjoy the effect!
Think this post is worth a read? Challenge your friends to check it out by liking and sharing! Let’s see who engages first. 🎯👥