HTML5 Canvas Game Engine: Build One in JavaScript

By Arron R.10 min read
An HTML5 canvas game engine is JavaScript that runs a game loop over the HTML canvas element: clear, update, redraw, read input, check collisions. Write a small

An HTML5 canvas game engine is the JavaScript code that turns a blank canvas element in a web page into a running game: it repeats a loop many times a second, reads the keyboard or touch screen, moves things around, checks what hit what, and redraws the picture. You can write a small one in an afternoon, use an existing framework, or have an AI write it for you. This guide explains how the pieces fit, gives you a working engine to copy, and shows where each option makes sense.

What is an HTML5 canvas game engine?

The canvas element is a rectangle of pixels on a web page. On its own it does nothing; you draw into it with JavaScript through the Canvas 2D API: rectangles, lines, text and images. A canvas has no memory of what you drew. It is a painting, not a list of objects, so if a character moves, you erase the canvas and paint the whole scene again.

That is why games need an engine on top. An HTML5 canvas game engine handles the jobs every game repeats:

  • The game loop: a function that runs every frame (one redraw of the screen), usually about 60 times a second.
  • Rendering: clearing the canvas and drawing every visible object in the right order.
  • Input: tracking which keys, mouse buttons or touches are active.
  • Collision and physics: detecting overlaps, applying gravity, stopping the player at walls.
  • Assets: loading images, sprite sheets (one image holding many animation frames in a grid) and sounds before the game starts.
  • Scenes: switching between a title screen, levels and a game-over screen.

Some people use “engine” only for big tools with editors, such as PlayCanvas, and call code libraries “frameworks”. In practice, any JavaScript HTML5 game engine is a bundle of the six jobs above. The difference between a 70-line engine and a large framework is how many edge cases each one has already solved.

The game loop: how a canvas engine runs every frame

Game development is built around one central timing loop. In the browser, the correct way to run it is requestAnimationFrame, which asks the browser to call your function just before the next screen refresh. It pauses automatically when the tab is hidden, which saves battery, and it lines up with the display so animation looks smooth.

Each pass through the loop does four things in order:

  1. Read input that arrived since the last frame.
  2. Update the game state: positions, velocities, timers, score.
  3. Clear the canvas.
  4. Draw everything again from the new state.

The one detail beginners miss is time. Screens refresh at different rates: 60Hz on many laptops, 120Hz or more on newer phones and gaming monitors. If you move a character 3 pixels per frame, it runs twice as fast on a 120Hz screen. The fix is to multiply movement by the elapsed time (often called dt, for delta time) so speed is measured in pixels per second, not pixels per frame.

A better version uses a fixed timestep: the update always advances the game by exactly 1/60 of a second, and the loop runs as many updates as real time requires before drawing. Physics then behaves identically on every machine, which matters the moment you add jumping or collisions.

Circular diagram of a canvas game loop: input, update, clear and draw
Every canvas engine repeats the same four steps, usually 60 times a second.

Build a tiny HTML5 canvas game engine in JavaScript

Here is a complete, minimal HTML5 canvas game engine with a fixed-timestep loop, keyboard input, collision and a score. Save it as game.js, include it from an empty HTML page with a script tag, and open the page in a browser. Move the blue square with the arrow keys to collect the yellow coins.

// game.js: a tiny canvas engine with a fixed-timestep loop
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 360;
canvas.style.background = "#111";
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");

// Input: remember which keys are held down
const keys = new Set();
addEventListener("keydown", (e) => keys.add(e.code));
addEventListener("keyup", (e) => keys.delete(e.code));

// Game state
const player = { x: 50, y: 50, w: 32, h: 32, speed: 200, color: "#4fc3f7" };
const coin = { x: 400, y: 200, w: 16, h: 16, color: "#ffd54f" };
let score = 0;

// Axis-aligned bounding box collision
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 (keys.has("ArrowLeft")) player.x -= player.speed * dt;
  if (keys.has("ArrowRight")) player.x += player.speed * dt;
  if (keys.has("ArrowUp")) player.y -= player.speed * dt;
  if (keys.has("ArrowDown")) player.y += player.speed * dt;

  // Keep the player on screen
  player.x = Math.max(0, Math.min(canvas.width - player.w, player.x));
  player.y = Math.max(0, Math.min(canvas.height - player.h, player.y));

  if (overlaps(player, coin)) {
    score += 1;
    coin.x = Math.random() * (canvas.width - coin.w);
    coin.y = Math.random() * (canvas.height - coin.h);
  }
}

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = coin.color;
  ctx.fillRect(coin.x, coin.y, coin.w, coin.h);
  ctx.fillStyle = player.color;
  ctx.fillRect(player.x, player.y, player.w, player.h);
  ctx.fillStyle = "#fff";
  ctx.font = "16px monospace";
  ctx.fillText("Score: " + score, 10, 20);
}

// Fixed timestep: update in 1/60 s steps, draw once per frame
const STEP = 1 / 60;
let last = performance.now();
let acc = 0;

function frame(now) {
  acc += Math.min((now - last) / 1000, 0.25); // cap long pauses
  last = now;
  while (acc >= STEP) {
    update(STEP);
    acc -= STEP;
  }
  render();
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

How the pieces map to engine jobs

  • Input is a Set of held keys, so update code asks “is Left down?” instead of reacting to events mid-frame.
  • Update only changes numbers. It never draws.
  • Render only draws. It never changes state. Keeping these apart is what lets you later pause, replay or network the game.
  • The 0.25 cap stops a “spiral of death” when the tab was hidden: without it, the loop would try to catch up thousands of updates at once.

Drawing sprites instead of rectangles

To swap the squares for art, load an image and use ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh). The first four numbers pick one frame out of a sprite sheet; the last four place it on the canvas. Advance sx by one frame width every few updates and you have animation. Sprites should be PNGs with transparent backgrounds so the canvas can blend them over the level, a technique called alpha compositing. Set ctx.imageSmoothingEnabled = false for pixel art, or the browser blurs it when scaling.

Adding physics and collision to a 2D canvas engine

Building a 2D game physics engine using HTML5 and JavaScript sounds big, but most 2D games need only three ideas.

1. Velocity and gravity

Give each moving object a velocity (vx, vy) in pixels per second. Each update, add gravity to vy, then add velocity to position:

const GRAVITY = 900; // pixels per second squared
const groundY = 320;

function applyPhysics(body, dt) {
  body.vy += GRAVITY * dt;
  body.x += body.vx * dt;
  body.y += body.vy * dt;
  body.onGround = false;
  if (body.y + body.h > groundY) {
    body.y = groundY - body.h;
    body.vy = 0;
    body.onGround = true;
  }
}

// Jump only when standing on something
function tryJump(body) {
  if (body.onGround) body.vy = -450;
}

2. Collision detection

The overlaps function in the engine above is AABB collision (axis-aligned bounding boxes: rectangles that never rotate). It covers platformers, top-down games and most arcade games. Circles are the next step: two circles touch when the distance between their centres is less than the sum of their radii. Rotated shapes need techniques such as the separating axis theorem, which is usually the point to reach for a library.

3. Collision response

Detecting a hit is easy; deciding what happens is the hard part. For solid walls, move the object on one axis, check for overlap, push it back out, then repeat for the other axis. Resolving X and Y separately is what stops a player from snagging on the corners between floor tiles.

Fast objects can pass through thin walls in a single step, a bug called tunnelling. Fixed timesteps, thicker colliders or splitting large moves into smaller steps all help. If your design leans on stacking boxes, ragdolls or rotating rigid bodies, use an existing physics library rather than writing one.

Phaser, PlayCanvas or your own engine?

A hand-written engine is the best way to learn, but you will soon want tilemaps, sprite animation, audio, cameras and scaling. That is the point to adopt an existing JavaScript HTML5 game engine. Two names come up most often.

Phaser is a free 2D framework for HTML5 games on desktop and mobile, and it can render through both canvas and WebGL. You keep writing JavaScript, but loops, loaders, physics and input are already done.

For 3D, you leave the Canvas 2D API behind. PlayCanvas is an open-source HTML5 3D engine built on WebGL, released under the MIT licence, with rigid-body physics, 3D audio and animation, and a browser-based editor that several people can use at once. It still renders into a canvas element, but through the GPU. Three.js is the other common route to an HTML5 3D game engine setup, as a rendering library you build game logic around.

OptionBest forTrade-off
Your own canvas engineLearning, game jams, tiny gamesYou solve every edge case yourself
Phaser2D games of any sizeA framework to learn; its structure shapes your code
PlayCanvas3D games and interactive 3D scenes3D asset pipeline and WebGL concepts to learn
Three.jsCustom 3D renderingA renderer, not a full game engine
WizardGenieGoing from an idea to playable code fastYou still review and steer what the AI writes

Many more exist: Wikipedia keeps a broad list of game engines if you want to compare. For a 2D browser game, though, Phaser or a hand-written HTML5 canvas game engine covers the vast majority of projects.

What changes for mobile and multiplayer

An HTML5 mobile game engine is the same engine with three additions: touch input alongside keys, canvas scaling for different screen sizes and pixel densities (set the canvas width to the CSS width times devicePixelRatio for sharp output), and a lighter draw budget for phone GPUs.

A multiplayer HTML5 game engine adds networking outside the canvas. The canvas only draws. A server, usually reached over WebSockets, holds the true game state; clients send inputs and render what the server says, predicting their own movement to hide lag. Because the engine above already separates update from render, it is ready for that split.

Comparison of a hand-written canvas engine, Phaser and PlayCanvas
Pick the layer that matches your game: hand-written, 2D framework or 3D engine.

Common mistakes when building a canvas game

  • Using setInterval for the loop. It drifts, ignores the display refresh and keeps running in hidden tabs. Use requestAnimationFrame.
  • Moving per frame instead of per second. The game runs at different speeds on different screens. Multiply by dt or use a fixed timestep.
  • Forgetting to clear the canvas. Every object leaves a smeared trail. Call clearRect (or draw a full background) first.
  • Drawing before images load. drawImage on an unloaded image draws nothing. Load every asset, wait for all of them, then start the loop.
  • Mixing logic into render. When drawing code changes game state, pausing and networking break in confusing ways.
  • Blurry pixel art. Disable image smoothing and scale by whole numbers.
  • Over-scoping the engine. Writing a scene editor before you have a fun level is how jam games die. Build only what the current game needs.

If you are new to the wider process, our guide to video game development for beginners covers scoping and first projects.

Skip the boilerplate with WizardGenie

Understanding the loop is valuable. Typing it out for the tenth time is not. WizardGenie is the AI game engine inside Sorceress: you describe the game you want, and it writes the code, runs it and iterates on it in real time. Instead of starting from an empty file, you start from a playable build and steer.

A practical way to use it with everything above:

  1. Describe the game and the stack. For example: “A top-down coin collector using the Canvas 2D API, fixed-timestep loop, arrow keys and touch controls, score in the corner.” If you want a framework, ask for Phaser instead.
  2. Play the running build and ask for changes in plain English: “Add gravity and a jump,” “Stop the player tunnelling through thin walls,” “Scale the canvas for phones.”
  3. Read the code it writes. With the concepts from this guide, you can spot whether update and render are separated and whether movement uses delta time, and ask for fixes when they are not.
  4. Swap models when useful. WizardGenie drives the leading AI coding models, and you can switch between them freely with your own API key.

It runs on the web with nothing to install, and as a Windows desktop app with an auto-updater that adds native file access and longer agent sessions. When the game is done, export the build and host it wherever you like. The WizardGenie overview explains the engine in more detail.

Art for your canvas game

Rectangles are fine for a prototype, but players want characters. Auto-Sprite v2 (Pro) creates game-ready 2D sprites, characters, items and effects in any art style, ready to slice with drawImage. For quick fixes to a sprite or background, Sorceress Canvas is a free, quick and easy in-browser image editor; despite the shared name, it is an image editor, not the HTML canvas element. If your AI agent should generate assets on its own, a key from the Sorceress API lets WizardGenie, or another coding agent, generate sprites, 3D models, music and sound effects. For audio, Sound Studio handles music, SFX and voice. The tools guide lists everything in one place.

The workflow at a glance

  1. Learn the core: run the 70-line engine above until the loop, input, update and render split make sense.
  2. Add only what your game needs: gravity, AABB collision, sprite sheet animation.
  3. Pick your layer: stay hand-written for jams and small games, move to Phaser for larger 2D projects, or PlayCanvas or Three.js for 3D.
  4. Plan for mobile and multiplayer early by keeping state and drawing separate.
  5. Use WizardGenie to generate and iterate on the code, and Sorceress art and audio tools to replace placeholder rectangles.

An HTML5 canvas game engine is not magic: it is a loop, a clear, a redraw and some careful bookkeeping. Once you have seen the whole thing in one file, every framework becomes easier to read, and every AI-written game becomes easier to steer.

Frequently Asked Questions

What is the best HTML5 canvas game engine for beginners?

For 2D games, Phaser is the common starting point: it is free, open source, renders with both canvas and WebGL, and has years of examples. Writing a tiny engine yourself first is still worth an afternoon, because it teaches you what Phaser is doing for you. If you would rather describe the game than write the loop, WizardGenie can generate and run the code for you.

Is HTML5 canvas fast enough for games?

Yes, for most 2D games. The Canvas 2D API comfortably handles platformers, shooters, puzzle games and top-down RPGs with hundreds of sprites. It slows down when you redraw thousands of objects every frame or apply heavy per-pixel effects. At that point, a WebGL renderer, which Phaser and PlayCanvas both use, moves the drawing work onto the GPU and keeps the frame rate steady.

Can you make 3D games with an HTML5 canvas game engine?

Not with the Canvas 2D context alone; it only draws flat shapes, images and text. 3D in the browser uses WebGL, which also renders into a canvas element but talks to the GPU. Engines such as PlayCanvas and libraries such as Three.js wrap WebGL so you work with meshes, cameras and lights instead of raw shader code.

Do HTML5 canvas games work on mobile phones?

Yes. Modern mobile browsers support canvas, so the same game runs on phones and desktops. You need to add touch input alongside keyboard input, scale the canvas to different screen sizes and pixel densities, and keep draw calls light for weaker GPUs. Testing on several aspect ratios early saves painful layout fixes later.

Can I build a multiplayer game with an HTML5 canvas engine?

Yes, but the networking lives outside the canvas. The canvas only draws; a server, usually reached through WebSockets, holds the authoritative game state and relays player inputs. Each client predicts its own movement and smooths other players between server updates. Start with a turn-based or slow-paced game before attempting fast real-time action.

Sources

  1. Phaser (game framework) — Wikipedia
  2. PlayCanvas — Wikipedia
  3. Alpha compositing — Wikipedia
  4. List of game engines — Wikipedia
Written by Arron R.·2,429 words·10 min read

Related posts