TExcelTAD
Home › 2D Games with JavaScript & Canvas › Canvas Games Intro

Canvas Games Intro

This course teaches you to make 2D games with nothing but a web browser: one <canvas> element, plain JavaScript and no framework. You will build four classic games from scratch (Pong, Breakout, a top-down shooter and a platformer), then add the polish that makes a game feel good, and finally look at the frameworks and tools that studios use.

The difference from a normal tutorial: every game in this course is playable inside the lesson. Each step of each project is a complete program in an editable playground. Click it, play it, change a number, press Run and play again.

Try it now

Click the game below, then use the arrow keys (or WASD) to steer the ship and collect the yellow coins. Click anywhere outside the game to pause it.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

const ship = { x: 240, y: 135, r: 10, speed: 170 };
const coin = { x: 380, y: 70, r: 7 };
let score = 0, t = 0;

function placeCoin() {
  coin.x = 20 + Math.random() * (W - 40);
  coin.y = 40 + Math.random() * (H - 60);
}

function update(dt) {
  t += dt;
  let dx = 0, dy = 0;
  if (keys.has('ArrowLeft') || keys.has('KeyA')) dx -= 1;
  if (keys.has('ArrowRight') || keys.has('KeyD')) dx += 1;
  if (keys.has('ArrowUp') || keys.has('KeyW')) dy -= 1;
  if (keys.has('ArrowDown') || keys.has('KeyS')) dy += 1;
  const len = Math.hypot(dx, dy) || 1;              // same speed on diagonals
  ship.x = Math.max(ship.r, Math.min(W - ship.r, ship.x + (dx / len) * ship.speed * dt));
  ship.y = Math.max(ship.r, Math.min(H - ship.r, ship.y + (dy / len) * ship.speed * dt));
  if (Math.hypot(ship.x - coin.x, ship.y - coin.y) < ship.r + coin.r) {
    score++;
    placeCoin();
  }
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  // coin, gently pulsing
  ctx.fillStyle = '#ffd54f';
  ctx.beginPath();
  ctx.arc(Math.round(coin.x), Math.round(coin.y), coin.r + Math.sin(t * 6), 0, Math.PI * 2);
  ctx.fill();
  // ship
  ctx.fillStyle = '#4fc3f7';
  ctx.beginPath();
  ctx.arc(Math.round(ship.x), Math.round(ship.y), ship.r, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillStyle = '#fff';
  ctx.font = '16px system-ui, sans-serif';
  ctx.textAlign = 'left';
  ctx.fillText('Coins: ' + score, 10, 22);
}

run(update, draw, 'Arrow keys or WASD to move');
</script>

That is a whole game in about 50 lines of game code: a player, a goal, a score. Everything else in this course is a bigger version of the same idea.

How the playable lessons work

Every game playground runs in a sandboxed frame on the lesson page. Three details make that work well for games, and you will see them at the top of every game in the course as the play kit:

Problem What the play kit does
A frame only receives keys after it has focus The canvas gets tabIndex = 0; clicking it calls canvas.focus(). Until then the game shows Click to play
Arrow keys and Space normally scroll the lesson page The game calls preventDefault() on those keys, so they move your character instead
A game that keeps running while you read wastes battery When the canvas loses focus (you click outside), the game pauses and keys are released
Games must run at the same speed on 60 Hz and 144 Hz screens A fixed-step loop calls update(1/60) a steady 60 times per second, whatever the screen's refresh rate

You will build each of these pieces yourself in the next lessons, so nothing in the kit stays magic. From then on the kit is a fixed block of about 35 lines at the top of every game, and the game itself is the code below the end of play kit comment.

Tip: The frame is 280 pixels tall. Drag its bottom edge to make it taller; the game scales up to fill it while keeping its shape.

What you will build

Project You learn
Pong Input, movement, collision, scoring, game states, restarting
Breakout Collision response, many objects, removing objects, levels, win/lose, sound with Web Audio
Top-down shooter Aiming with the mouse, projectiles, cooldowns, enemy spawning, health, object pooling
Platformer Gravity, jumping that feels good (coyote time, jump buffering), tilemaps, camera follow, checkpoints
Star Catcher (mini project) A finished game with start, pause, win and lose screens, saved high score

Along the way you will also write small pure-logic functions (collision tests, the fixed-step accumulator, an object pool, tile collision) as js run examples with printed output. Game logic you can test without a screen is game logic you can trust.

What you need to know first

  • JavaScript basics: variables, functions, arrays, objects and classes. The JavaScript course covers all of them.
  • A little HTML: what a <canvas> and a <script> element are. The HTML Canvas lesson is a good warm-up.
  • School maths: coordinates, a bit of trigonometry (Math.sin, Math.cos, Math.atan2) and Pythagoras (Math.hypot). Each lesson explains what it uses.

Why raw canvas first?

Engines such as Phaser, Unity or Godot hide the game loop, input handling and collision behind ready-made systems. That is great when you ship, but it is hard to debug a system you have never seen from the inside. After this course you will know what those systems do, and the Toolkit section shows how the same ideas look in Phaser 3, PixiJS and Kaplay.

Test yourself

Why does each game in this course show **Click to play** first?

  1. The browser forbids JavaScript until you click
  2. The game frame only receives keyboard events after it has focus, and clicking gives it focus
  3. Canvas cannot draw before a click
  4. To load images from a server

What would happen to the lesson page if a game did **not** call preventDefault() on arrow keys?

  1. Nothing, frames never affect the page
  2. The arrow keys would scroll the lesson page while you play
  3. The game would crash
  4. The keys would be typed into the editor

Why divide the movement direction by its length (Math.hypot(dx, dy))?

  1. To make the ship faster diagonally
  2. So moving diagonally is not about 41% faster than moving straight
  3. Because canvas needs normalized coordinates
  4. To round positions to whole pixels