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:
- Read input that arrived since the last frame.
- Update the game state: positions, velocities, timers, score.
- Clear the canvas.
- 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.

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
Setof 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.





