Creating interactive games with the HTML5 Canvas API is a great way to enhance your JavaScript skills while making something fun and functional. Let’s build a basic interactive game: a Bouncing Ball Game. You’ll learn the basics of working with Canvas, creating animations, handling collisions, and adding user interactivity.
Project Overview
Game: Bouncing Ball Game
Features:
- A ball moves and bounces off the edges of the canvas.
- The user can control the ball’s movement using arrow keys.
- Basic collision detection with canvas boundaries.
Step 1: Set Up Project Structure
Create the following files:
/BouncingBallGame
│
├── index.html
├── styles.css
└── script.js
Step 2: Write HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bouncing Ball Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Bouncing Ball Game</h1>
<canvas id="gameCanvas"></canvas>
<script src="script.js"></script>
</body>
</html>
Step 3: Style the Canvas (styles.css)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #282c34;
font-family: Arial, sans-serif;
color: white;
flex-direction: column;
}
h1 {
margin-bottom: 10px;
}
canvas {
border: 2px solid white;
}
Step 4: Add JavaScript Logic (script.js)
// Select the canvas and set its context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Set canvas size
canvas.width = 800;
canvas.height = 400;
// Ball properties
let ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 20,
dx: 5, // Velocity in X direction
dy: 4, // Velocity in Y direction
};
// Handle keyboard controls
let keys = {};
window.addEventListener('keydown', (e) => keys[e.key] = true);
window.addEventListener('keyup', (e) => keys[e.key] = false);
// Draw the ball on the canvas
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = 'tomato';
ctx.fill();
ctx.closePath();
}
// Update ball position and handle collisions
function updateBall() {
if (keys['ArrowRight'] && ball.x + ball.radius < canvas.width) ball.x += ball.dx;
if (keys['ArrowLeft'] && ball.x - ball.radius > 0) ball.x -= ball.dx;
if (keys['ArrowUp'] && ball.y - ball.radius > 0) ball.y -= ball.dy;
if (keys['ArrowDown'] && ball.y + ball.radius < canvas.height) ball.y += ball.dy;
// Reverse direction if ball hits horizontal walls
if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
ball.dx = -ball.dx;
}
// Reverse direction if ball hits vertical walls
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.dy = -ball.dy;
}
ball.x += ball.dx;
ball.y += ball.dy;
}
// Clear the canvas
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
// Game loop: Draw, update, and animate
function gameLoop() {
clearCanvas();
drawBall();
updateBall();
requestAnimationFrame(gameLoop);
}
// Start the game loop
gameLoop();
Step 5: Run the Game
- Open the
index.html
file in your browser.
- Use the arrow keys to control the ball’s movement.
- Watch the ball bounce off the canvas boundaries.
Explanation
- HTML Canvas Setup: The
<canvas>
element creates a drawing surface in the browser.
- JavaScript Canvas API: We use the
getContext('2d')
method to draw 2D shapes, like the ball.
- Animation: The
requestAnimationFrame()
function runs the gameLoop()
function continuously to create smooth animations.
- Keyboard Events: We capture the arrow key events to move the ball on the canvas.
- Collision Detection: When the ball touches the canvas borders, we reverse its direction.
Possible Enhancements
- Add multiple balls with different colors.
- Introduce obstacles or targets to hit with the ball.
- Display a score counter based on time or interactions.
- Create levels with increasing difficulty.
Conclusion
This interactive game with HTML5 Canvas demonstrates the power of JavaScript for creating browser-based games. You’ve implemented a smooth animation loop, handled keyboard input, and created a basic collision detection system.
Feel free to expand this project with new features and functionality to make it more challenging! Let me know if you'd like to add more features or create other games.