Chapter 76: Game Canvas
1. What is “Game Canvas” actually? (Very clear definition first)
Game Canvas means using the HTML <canvas> element + JavaScript to build games that run directly in web browsers — drawing characters, enemies, backgrounds, bullets, scores, animations, collisions, sound effects, everything pixel by pixel.
In simple words:
- <canvas> = your game screen / drawing board
- JavaScript = the brain (move player, detect collision, update score, handle keyboard/mouse/touch)
- Browser = the game engine (no need to install Unity, Godot, or download app)
Why Game Canvas is perfect for students & beginners:
- Zero installation — just open .html file in Chrome/Firefox
- Works on phone/tablet/laptop — no app store needed
- Learn real JavaScript skills (loops, events, math, animation, logic)
- Very fast to make something playable (Snake game in 1–2 hours)
- Share easily — GitHub, CodePen, Netlify, your website
- College project favorite — looks impressive in viva/resume
2. Game Canvas vs Other Game Tech (Quick Comparison)
| Tech | Difficulty | Installation needed? | Works in browser? | Best for beginners? | Example games |
|---|---|---|---|---|---|
| Game Canvas | ★★★☆☆ | No | Yes | Yes | Snake, Pong, Flappy Bird |
| Phaser.js (Canvas lib) | ★★☆☆☆ | Yes (npm) | Yes | Very yes | Platformers, RPGs |
| Unity | ★★★★☆ | Yes (big download) | No (WebGL export) | No | 3D games, AAA games |
| HTML DOM games | ★★☆☆☆ | No | Yes | Yes | Tic-tac-toe, memory cards |
Game Canvas = raw power — you control every pixel, but learn deeply.
3. Core Game Canvas Concepts (Must Know These 5 Things)
Every Game Canvas project has this 60fps loop:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function gameLoop() { // 1. UPDATE: move player, enemies, bullets (logic) update(); // 2. DRAW: clear screen + redraw everything draw(); // 3. Next frame (60 times per second) requestAnimationFrame(gameLoop); } |
The 5 pillars of Game Canvas:
- Input — keyboard, mouse, touch
- Update — move objects, collision, score
- Draw — clearRect() + draw shapes/images/text
- Collision — check if player hits enemy
- Game state — menu, playing, game over, win
4. Your First Game Canvas – Moving Player with Arrow Keys (Copy-Paste & Run)
Create game-canvas-first.html:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Game Canvas – Moving Player</title> <style> body { background: #1a1a2e; margin: 0; display: flex; flex-direction: column; align-items: center; font-family: Arial, sans-serif; } canvas { border: 4px solid #34495e; background: #16213e; border-radius: 10px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); } h1 { color: #ecf0f1; margin: 20px 0; } </style> </head> <body> <h1>Game Canvas – Move Blue Square with Arrow Keys</h1> <p>Use ← → ↑ ↓ or WASD keys | Stay inside screen</p> <canvas id="gameCanvas" width="800" height="600"></canvas> <script> // === GAME CANVAS SETUP === const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // Player object (blue square) const player = { x: 380, // starting position y: 280, width: 40, height: 40, speed: 6 // pixels per frame }; // Keyboard input (WASD + arrows) const keys = {}; // Listen for key presses window.addEventListener('keydown', (e) => { keys[e.key.toLowerCase()] = true; }); window.addEventListener('keyup', (e) => { keys[e.key.toLowerCase()] = false; }); // === UPDATE: move player === function update() { // Move up if (keys['arrowup'] || keys['w']) { player.y -= player.speed; } // Move down if (keys['arrowdown'] || keys['s']) { player.y += player.speed; } // Move left if (keys['arrowleft'] || keys['a']) { player.x -= player.speed; } // Move right if (keys['arrowright'] || keys['d']) { player.x += player.speed; } // Keep player inside canvas player.x = Math.max(0, Math.min(canvas.width - player.width, player.x)); player.y = Math.max(0, Math.min(canvas.height - player.height, player.y)); } // === DRAW: clear + redraw everything === function draw() { // Clear screen (black background) ctx.fillStyle = '#16213e'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw player (blue square) ctx.fillStyle = '#3498db'; ctx.fillRect(player.x, player.y, player.width, player.height); // Player outline ctx.strokeStyle = '#5dade2'; ctx.lineWidth = 4; ctx.strokeRect(player.x, player.y, player.width, player.height); // Instructions ctx.fillStyle = '#ecf0f1'; ctx.font = 'bold 24px Arial'; ctx.textAlign = 'center'; ctx.fillText('Use Arrow Keys or WASD to Move', canvas.width/2, 40); } // === MAIN GAME LOOP (60fps) === function gameLoop() { update(); // Move draw(); // Redraw requestAnimationFrame(gameLoop); // Next frame } // Start the game! gameLoop(); </script> </body> </html> |
What happens when you run it:
- Dark game screen with blue square in center
- Use arrow keys or WASD → square moves smoothly
- Stays inside screen borders
- Runs at 60fps (smooth)
This is your first real Game Canvas — player movement + game loop working!
5. Next Level – Add Enemy + Collision (Copy-Paste & Upgrade)
Replace the entire <script> with this upgraded version:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // Player (blue square) const player = { x: 380, y: 280, width: 40, height: 40, speed: 6 }; // Enemy (red square - moves randomly) const enemy = { x: 100, y: 100, width: 40, height: 40, speed: 2 }; // Score let score = 0; const keys = {}; window.addEventListener('keydown', (e) => keys[e.key.toLowerCase()] = true); window.addEventListener('keyup', (e) => keys[e.key.toLowerCase()] = false); function update() { // Move player if (keys['arrowup'] || keys['w']) player.y -= player.speed; if (keys['arrowdown'] || keys['s']) player.y += player.speed; if (keys['arrowleft'] || keys['a']) player.x -= player.speed; if (keys['arrowright'] || keys['d']) player.x += player.speed; // Keep player in bounds player.x = Math.max(0, Math.min(canvas.width - player.width, player.x)); player.y = Math.max(0, Math.min(canvas.height - player.height, player.y)); // Move enemy randomly enemy.x += (Math.random() - 0.5) * enemy.speed * 4; enemy.y += (Math.random() - 0.5) * enemy.speed * 4; // Keep enemy in bounds enemy.x = Math.max(0, Math.min(canvas.width - enemy.width, enemy.x)); enemy.y = Math.max(0, Math.min(canvas.height - enemy.height, enemy.y)); // Collision detection (player touches enemy) if (checkCollision(player, enemy)) { score++; enemy.x = Math.random() * (canvas.width - enemy.width); enemy.y = Math.random() * (canvas.height - enemy.height); } } function checkCollision(rect1, rect2) { return rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.y + rect1.height > rect2.y; } function draw() { ctx.fillStyle = '#16213e'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw player ctx.fillStyle = '#3498db'; ctx.fillRect(player.x, player.y, player.width, player.height); ctx.strokeStyle = '#5dade2'; ctx.lineWidth = 4; ctx.strokeRect(player.x, player.y, player.width, player.height); // Draw enemy ctx.fillStyle = '#e74c3c'; ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height); ctx.strokeStyle = '#c0392b'; ctx.strokeRect(enemy.x, enemy.y, enemy.width, enemy.height); // Score ctx.fillStyle = '#ecf0f1'; ctx.font = 'bold 36px Arial'; ctx.textAlign = 'center'; ctx.fillText(`Score: ${score}`, canvas.width / 2, 50); ctx.font = '20px Arial'; ctx.fillText('Touch red square to score! Arrow keys / WASD', canvas.width / 2, canvas.height - 30); } function gameLoop() { update(); draw(); requestAnimationFrame(gameLoop); } gameLoop(); </script> |
What happens now:
- Red enemy square moves randomly
- Touch it with blue player → score +1 + enemy jumps to new position
- Real collision detection working!
6. Teacher’s Quick Summary – Game Canvas Golden Rules
| Step in Game Loop | What it does | Code example |
|---|---|---|
| Update | Move player/enemies, check collision, update score | player.x += speed / collision function |
| Draw | clearRect() + draw everything fresh | ctx.fillRect() / ctx.fillText() |
| Loop | requestAnimationFrame(gameLoop) — 60fps smooth | Runs forever automatically |
| Input | Keyboard/mouse/touch events | addEventListener(‘keydown’) |
Understood Game Canvas fully now? This is the foundation of every browser game — Snake, Flappy Bird, Asteroids, all start exactly like this.
Tell me honestly — what do you want next?
- Full Snake game (eat food, grow, game over)?
- Pong (ball + paddles + score)?
- Flappy Bird clone?
- Add sound effects + win/lose screen?
- Or 20-question Game Canvas quiz?
Just say — we can build any game together step by step! 🚀
