SSantoshi/GamesSearch

Programming

Make a browser game with HTML5 canvas and JavaScript

No engine, no install: build a complete dodge game in about 100 lines of plain JavaScript that anyone can play from a link. Includes the full, tested code.

Every web browser can run games. You need a text editor, a browser and about 100 lines of JavaScript. In this guide you build Dodge: blocks fall from the sky, you slide left and right to avoid them, and the longer you survive, the faster they come. It's a complete game with a score, a game-over screen and a restart, and by the end it'll work on phones too.

Making a game without an engine is the best way to see what engines do for you. There are four jobs: a game loop, input, drawing and collisions. You'll write all four yourself, and none of them is more than a few lines.

If you'd rather start from working files, download the finished project (two files and a README, under 2 KB zipped) and read along.

1. The page

Create a folder with two files. First, index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dodge</title>
  <style>
    body { margin: 0; background: #111; display: grid; place-items: center; min-height: 100vh; }
    canvas { background: #1d1f1e; max-width: 100%; }
  </style>
</head>
<body>
  <canvas id="game" width="480" height="640"></canvas>
  <script src="game.js"></script>
</body>
</html>

The <canvas> element is a blank rectangle you can draw on with JavaScript. It's 480 by 640 pixels, and the style keeps it centred.

2. The game

Now game.js. Read it top to bottom. It's in the same order a game thinks.

const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');

// Keyboard state: true while a key is held down.
const keys = {};
addEventListener('keydown', (event) => {
  if ([' ', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.preventDefault();
  keys[event.key] = true;
});
addEventListener('keyup', (event) => {
  keys[event.key] = false;
});

let player, blocks, spawnTimer, score, gameOver;

function reset() {
  player = { x: 220, y: 580, w: 40, h: 40, speed: 320 };
  blocks = [];
  spawnTimer = 0;
  score = 0;
  gameOver = false;
}

// Axis-aligned rectangles overlap when they overlap on both x and y.
function overlaps(a, b) {
  return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}

function update(dt) {
  if (gameOver) {
    if (keys[' ']) reset();
    return;
  }

  if (keys.ArrowLeft) player.x -= player.speed * dt;
  if (keys.ArrowRight) player.x += player.speed * dt;
  player.x = Math.max(0, Math.min(canvas.width - player.w, player.x));

  spawnTimer -= dt;
  if (spawnTimer <= 0) {
    const size = 20 + Math.random() * 40;
    blocks.push({ x: Math.random() * (canvas.width - size), y: -size, w: size, h: size, speed: 150 + score * 4 });
    spawnTimer = Math.max(0.25, 0.9 - score * 0.01);
  }

  for (const block of blocks) block.y += block.speed * dt;
  blocks = blocks.filter((block) => block.y < canvas.height);

  if (blocks.some((block) => overlaps(player, block))) gameOver = true;
  score += dt;
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = '#d9fc52';
  ctx.fillRect(player.x, player.y, player.w, player.h);

  ctx.fillStyle = '#ff6b8b';
  for (const block of blocks) ctx.fillRect(block.x, block.y, block.w, block.h);

  ctx.fillStyle = '#f4f1e8';
  ctx.font = '20px sans-serif';
  ctx.fillText('Score: ' + Math.floor(score), 12, 28);

  if (gameOver) {
    ctx.textAlign = 'center';
    ctx.fillText('Game over! Press Space to restart', canvas.width / 2, canvas.height / 2);
    ctx.textAlign = 'left';
  }
}

let last = performance.now();
function frame(now) {
  const dt = Math.min((now - last) / 1000, 0.05); // seconds since last frame, capped
  last = now;
  update(dt);
  draw();
  requestAnimationFrame(frame);
}

reset();
requestAnimationFrame(frame);

Open index.html in your browser and play. Arrow keys move, Space restarts.

3. How it works

The input code doesn't act on key presses. It remembers which keys are held, in the keys object, and the game reads that every frame. That's what makes movement smooth instead of jerky. preventDefault stops the arrow keys and Space from scrolling the page.

The game loop is requestAnimationFrame. It asks the browser to call frame before the next screen refresh, usually 60 times a second, and every frame runs update (change the world) and then draw (show it). Keeping those two apart is a habit worth building now. Every engine does the same split.

dt is the number of seconds since the last frame. Multiplying speeds by it keeps the game the same speed on a 60 Hz laptop and a 144 Hz monitor. The cap of 0.05 seconds stops everything from teleporting if the tab was in the background. Our game loop and delta time guide explains this properly.

overlaps is the classic rectangle test, often called AABB (axis-aligned bounding box). Two boxes touch only if they overlap on the x axis and the y axis. It's fast and it's exact for rectangles, which is why so many 2D games use boxes for hitboxes even when the art is round.

The difficulty curve is two lines. Blocks fall faster (150 + score * 4) and spawn more often (0.9 - score * 0.01, never below a quarter of a second) the longer you survive. Change those numbers and you've made a different game.

Finally, blocks that fall off the bottom are removed with filter, so the list never grows forever. Forget that in a bigger game and it slowly gets slower the longer someone plays.

4. Make it work on phones

Right now a phone player can't move. Add this near the top of game.js, after the keyboard code:

// Hold the left or right half of the canvas to move; tap to restart.
let touchDir = 0;
canvas.addEventListener('pointerdown', (event) => {
  const rect = canvas.getBoundingClientRect();
  touchDir = event.clientX - rect.left < rect.width / 2 ? -1 : 1;
  if (gameOver) reset();
});
addEventListener('pointerup', () => (touchDir = 0));
addEventListener('pointercancel', () => (touchDir = 0));

Then replace the two keys.ArrowLeft / keys.ArrowRight lines in update with:

  const dir = (keys.ArrowRight ? 1 : 0) - (keys.ArrowLeft ? 1 : 0) + touchDir;
  player.x += Math.sign(dir) * player.speed * dt;

And add touch-action: none; to the canvas rule in the CSS, so a held finger doesn't scroll or zoom the page. Pointer events cover mouse, touch and pen with one set of handlers, so the same code also lets you play with a mouse.

5. Keep a best score

// localStorage can throw (private windows, sandboxed iframes), so never let it crash the game.
function loadBest() {
  try { return Number(localStorage.getItem('dodge-best')) || 0; } catch { return 0; }
}
function saveBest(value) {
  try { localStorage.setItem('dodge-best', String(value)); } catch { /* no storage: keep it in memory */ }
}
let best = loadBest();

In update, replace the collision line with:

  if (blocks.some((block) => overlaps(player, block))) {
    gameOver = true;
    if (Math.floor(score) > best) {
      best = Math.floor(score);
      saveBest(best);
    }
  }

And in draw, under the score: ctx.fillText('Best: ' + best, 12, 52);

The try/catch isn't paranoia. We learned it the hard way with our own arcade: games on our play pages run in a sandboxed iframe that isn't allowed any storage, and an unguarded localStorage call there throws and stops the game. It's why our games that save progress offer a separate "play full screen" page.

6. Sharp on high-resolution screens

On a phone or a laptop with a high-DPI screen, the canvas can look slightly blurry, because 480 canvas pixels are being stretched over 960 or more real ones. The fix is to make the canvas's pixel buffer bigger and scale the drawing:

const W = 480, H = 640;
const scale = window.devicePixelRatio || 1;
canvas.width = W * scale;
canvas.height = H * scale;
canvas.style.width = W + 'px';
ctx.scale(scale, scale);

Put that straight after getContext, then replace every canvas.width with W and canvas.height with H in the rest of the code. The game logic keeps thinking in 480 × 640, and the browser gets a crisp image. Leave max-width: 100% in the CSS so the canvas still shrinks on small screens.

7. Engine or no engine?

For a game this size, plain JavaScript is perfect. The whole thing is a few kilobytes and loads instantly. It starts to hurt when you want sprite animation, sound mixing, tilemaps, physics or scenes. You can write all of those yourself, and it's a great way to learn, but it's slow.

At that point you have two good options. A JavaScript framework like Phaser keeps you in the browser and handles sprites, physics, sound and scenes. Or an engine like Godot, which has an editor and exports to the web. All of our own games are made in Godot and run in the browser that way. Having written a game loop by hand, you'll understand exactly what either one is doing for you.

What we learned building the Santoshi Arcade

Every game in our arcade talks to the web page around it the same way a small canvas game can, and the lesson applies to anything you embed in a page.

The game never talks to our server directly. It posts two kinds of message to the page that contains it, using window.parent.postMessage: start when a run begins, and exactly one score when it ends. The page checks that the message really came from its own game frame and only then records the run. That separation means a player can't post a score just by typing into the browser console, and it means one bridge works for every game, whatever it's made in.

If you put Dodge in an arcade like ours, the change is two lines: send start in reset() and score where gameOver becomes true. Thinking about exactly where a "run" begins and ends turns out to be a useful design exercise on its own. Should a restart halfway through count as a new run? (In our arcade, yes, and the abandoned run's score is sent first.)

8. Share it

Zip index.html and game.js together and upload the zip to itch.io as an HTML game. People can play it from a link, on any device with a browser. Our itch.io publishing guide shows every step. And if you want a list of ideas to try next: a rare green block that slows everything for three seconds, a short sound with new Audio('hit.wav').play() on game over, or blocks that drift sideways as well as down.


Sources & credits

This guide is original writing by Santoshi Games. It draws on, and links to, the free resources below. All rights to them belong to their creators. Please support them.

Questions people ask

Do I need Phaser or another library to make a browser game?
No. A small browser game needs only an HTML page, a canvas element and some JavaScript: a game loop with requestAnimationFrame, keyboard or touch input, drawing, and simple collision checks. This guide's Dodge game does all four in two files and a few kilobytes. Reach for Phaser, or an engine like Godot, once you need sprite animation, sound mixing, tilemaps, physics or scenes.
How do I animate a character from a sprite sheet on an HTML canvas?
Load the sheet as an Image, then draw one frame at a time with the nine-argument form of drawImage, which takes a source rectangle on the sheet and a destination rectangle on the canvas. Keep a frame index and advance it by elapsed time rather than once per frame, so the animation runs at the same speed on 60 Hz and 120 Hz screens. For crisp pixel art, set imageSmoothingEnabled to false.
Where can I put my finished browser game online for free so friends can play?
itch.io is the easiest. Zip your index.html and game files, upload them as an HTML project, tick "This file will be played in the browser", and you get a link anyone can open on a phone or a PC. GitHub Pages, Netlify and Cloudflare Pages also host static games for free. Our itch.io guide walks through every setting on the upload page.
My canvas game gets laggy. What can I do to speed it up?
Profile it first with the Performance panel in your browser's DevTools, so you fix what's actually slow. The usual culprits: more than one animation loop, creating new objects every frame (which triggers garbage collection), redrawing a static background every frame instead of once to an offscreen canvas, and changing canvas state such as fonts and colours far more often than needed. Scale movement by delta time so slow frames don't change the game's speed.
← Back to learn