Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link.
๐ฎ Try the Live Interactive Demo ยท ๐ฆ GitHub Repo & Vitest Suite ยท โก Get the TS 2D Canvas Physics Starter Kit

Under the hood of 2D game physics: vector integration, collision normals, and impulse resolution in HTML5 Canvas.
What We Build Under the Hood
-
Semi-Implicit Euler Gravity: Two lines of
dt-scaled vector integration that turn static coordinates into falling bodies. -
Inverse Mass (
1 / m = 0): Modeling immovable walls and dynamic projectiles through one branch-free formula. - Impulse & Positional Correction: Resolving circle-to-circle collisions along surface normals without floor jitter.
- Matter.js Production Trade-offs: Porting our ~145-line custom solver to Matter.js to expose tunneling and engine boundaries.
A few weeks ago, I was reading a game development tutorial. It cheerfully announced: "Physics sounds intimidating... but don't worry, a physics engine will handle all the math for you!" With a single line of code, the author attached physics to a ball. The ball dropped, bounced off the floor, and everyone went home happy.
That sentence genuinely bothered me.
Because if you don't understand what happens beneath that single line of code, the engine remains a complete black box. Why does the ball bounce at that exact speed? Why does tweaking gravity suddenly make everything feel floaty or jittery? What actually happens when two bodies overlap? You end up hunting through engine docs for mysterious configuration parameters โ without even knowing what physical phenomena you are trying to configure.
Using an off-the-shelf physics engine is a lot like driving a car without ever popping the hood: it's comfortable, it's fast, and most days it's all you need. But when you understand the pistons, gears, and timing belts underneath, you don't get lost in documentation the moment a weird rattling sound starts coming from the chassis.
In this guide, we pop the hood and assemble the engine piece by piece: gravity, collision detection, impulse resolution, and elasticity. By the end, we'll have a fully playable slingshot game built on HTML5 Canvas. Then, we'll return to the "automatic transmission" โ Matter.js โ to answer an honest question: when should you build your own, and when should you use an established library?
Don't worry: every bit of math required for 2D game physics is straightforward high-school physics. Position, velocity, and a handful of vector operations. That's really it.

The three-phase browser game loop: measure delta time (dt), step the physics world, and redraw the 2D Canvas frame.
Setting the Stage: The Game Loop
At the heart of every game beats a steady pulse: the game loop. Roughly 60 times every second, it executes three distinct steps:
- Measure time (how many seconds elapsed since the previous frame?)
- Update the world (physics calculations live here)
- Render to screen (clearing and redrawing the Canvas)
In the browser, we build this loop around requestAnimationFrame. Much like the browser's event loop, requestAnimationFrame hooks directly into the browser's display refresh cycle, invoking our callback right before the screen paints:
// src/main.ts โ game loop (as implemented in the project)
let last = performance.now();
function frame(now: number) {
const dt = Math.min((now - last) / 1000, 1 / 30); // in seconds
last = now;
if (!dragging) world.step(dt); // 1. Advance physics
updateParticles(dt);
draw(); // 2. Render to screen
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
The variable dt stands for delta time โ the time elapsed between consecutive frames. Why is this critical? On a 120Hz display, frames arrive twice as often as on a 60Hz display. If your update logic simply says "move 5 pixels per frame", your game will run twice as fast on high-refresh hardware. But if you state "travel 300 pixels per second, moving 300 * dt each frame", the simulation moves at the exact same physical speed across any device.
Notice the Math.min(..., 1 / 30) cap. If a player switches browser tabs for five seconds and returns, an uncapped dt of 5.0 seconds would cause the ball to teleport straight through solid walls in a single frame. Capping delta time prevents catastrophic simulation instability. In Part 3: Metronome Physics โ Fixed Timestep Game Loops and Render Interpolation in TypeScript, we upgrade this variable dt step into a deterministic fixed-timestep accumulator loop across 60Hz and 144Hz monitors.
Vectors: The Alphabet of Physics
In a 2D coordinate space, almost every physical concept boils down to two numbers: x and y. Position is a vector, velocity is a vector, and gravity is a vector. At the foundation of our engine lies a lightweight vector math utility:
// src/engine/vec.ts
export type Vec2 = { x: number; y: number };
export const vec = (x = 0, y = 0): Vec2 => ({ x, y });
export const add = (a: Vec2, b: Vec2): Vec2 => vec(a.x + b.x, a.y + b.y);
export const sub = (a: Vec2, b: Vec2): Vec2 => vec(a.x - b.x, a.y - b.y);
export const scale = (a: Vec2, s: number): Vec2 => vec(a.x * s, a.y * s);
export const length = (a: Vec2): number => Math.hypot(a.x, a.y);
export const dot = (a: Vec2, b: Vec2): number => a.x * b.x + a.y * b.y;
export const normalize = (a: Vec2): Vec2 => {
const len = length(a);
return len === 0 ? vec() : scale(a, 1 / len);
};
Two functions in this module are our star players:
-
normalize: Strips away a vector's magnitude and preserves only its direction (reducing its length to 1). This answers: "In which direction did the collision occur?" -
dot(Dot Product): Measures the projection (the "shadow") of one vector onto another. This answers: "How much of the ball's velocity is heading directly perpendicular into the surface?"
In geometric terms, the dot product calculates the scalar projection of one vector along the axis of another. We'll see both in action shortly.

Modeling dynamic circles and immovable static obstacles with a single Body structure using inverse mass (invMass = 0).
Bodies: The Actors in Our World
In our engine, every dynamic body is a circle. This is an intentional architectural decision: circle-to-circle collision detection is a single distance check, whereas polygons and oriented bounding boxes introduce complex edge cases, vertex winding, and vertex-face tests. When learning the core mechanics, keep the geometry simple so the physics concepts remain crystal clear.
// src/engine/body.ts
import { type Vec2, vec } from "./vec";
export interface Body {
pos: Vec2;
vel: Vec2;
radius: number;
invMass: number; // 1/mass โ 0 for static bodies
bounciness: number; // 0 = no bounce, 1 = perfectly elastic
}
export function createBody(
x: number,
y: number,
radius: number,
opts: { static?: boolean; bounciness?: number } = {},
): Body {
return {
pos: vec(x, y),
vel: vec(),
radius,
invMass: opts.static ? 0 : 1 / (radius * radius),
bounciness: opts.bounciness ?? 0.6,
};
}
Notice the seemingly unusual property: instead of storing mass, we store invMass (inverse mass, 1 / mass). Why?
In physics engines, non-moving boundaries โ walls, floors, pillars โ are modeled as objects of infinite mass. In code, multiplying or dividing by Infinity leads to edge-case headaches and NaN values. But if you store inverse mass, an infinite mass turns cleanly into 0:
1 / โ = 0
During collision resolution, invMass acts as a direct multiplier: for a static body, multiplying by 0 immediately zeroes out any displacement or velocity change. That single number lets movable projectiles and immovable bedrock pass through the exact same mathematical formulas. A small numerical trick, but massive architectural elegance.
Additionally, setting 1 / (radius * radius) scales mass proportionally to the circle's 2D area: bigger circles are naturally heavier, smaller circles are lighter. Realistic physical weight for virtually zero code.

Semi-implicit Euler integration over discrete time steps: gravity accelerates velocity, and velocity advances position.
Gravity: A Two-Line Universe
Here is one of the most satisfying revelations in game programming. Gravity โ the phenomenon that sounds like complex astrophysics โ takes exactly two lines of code in our engine:
// src/engine/world.ts โ integration step
b.vel = add(b.vel, scale(this.gravity, dt)); // velocity += gravity * time
b.pos = add(b.pos, scale(b.vel, dt)); // position += velocity * time
Two lines. That's it.
Gravity accelerates velocity over time, and velocity alters position over time. Running these two lines on every tick causes objects to drop naturally. This technique is known as Euler integration โ the simplest numerical method for approximating Newton's differential equations over tiny discrete time steps. Production physics engines often employ higher-order numerical integrators like Verlet or Runge-Kutta 4 (RK4), but for a 2D game loop, Euler integration is remarkably effective.
Here is how our World class starts coming together:
// src/engine/world.ts โ world skeleton
export class World {
bodies: Body[] = [];
gravity: Vec2;
constructor(
public width: number,
public height: number,
gravityY = 900,
) {
this.gravity = vec(0, gravityY);
}
add(body: Body): Body {
this.bodies.push(body);
return body;
}
step(dt: number) {
// 1. Integration: gravity -> velocity -> position
for (const b of this.bodies) {
if (b.invMass === 0) continue; // Static bodies never fall
b.vel = add(b.vel, scale(this.gravity, dt));
b.pos = add(b.pos, scale(b.vel, dt));
}
// 2. Screen boundary collisions
for (const b of this.bodies) this.collideWalls(b);
// 3. Body-to-body collisions (each pair evaluated once)
for (let i = 0; i < this.bodies.length; i++) {
for (let j = i + 1; j < this.bodies.length; j++) {
this.collideBodies(this.bodies[i], this.bodies[j]);
}
}
}
}
Notice the default gravityY = 900. In real-world physics, gravitational acceleration is roughly 9.8 m/sยฒ. In Canvas, our coordinate system is measured in pixels, not meters. Across a viewport roughly 1000 pixels high, an acceleration of 900 px/sยฒ feels snappy and tangible. In game physics, tactile game feel consistently trumps pure textbook realism โ Angry Birds doesn't simulate real planetary gravitation, it simulates what feels good under your thumb.

Wall collision response: clamp overlapping geometry back inside the viewport first, then invert and dampen normal velocity.
Screen Boundaries: Our First Collision
Before our balls drop off the bottom of the monitor into oblivion, we need boundaries. Wall collisions provide the smoothest introduction to collision response because the surface normal (the perpendicular vector pointing away from the wall) is aligned directly with the coordinate axes:
// src/engine/world.ts โ World body method
private collideWalls(b: Body) {
if (b.invMass === 0) return;
if (b.pos.x - b.radius < 0) {
b.pos.x = b.radius;
b.vel.x = -b.vel.x * b.bounciness;
}
if (b.pos.x + b.radius > this.width) {
b.pos.x = this.width - b.radius;
b.vel.x = -b.vel.x * b.bounciness;
}
if (b.pos.y - b.radius < 0) {
b.pos.y = b.radius;
b.vel.y = -b.vel.y * b.bounciness;
}
if (b.pos.y + b.radius > this.height) {
b.pos.y = this.height - b.radius;
b.vel.y = -b.vel.y * b.bounciness;
}
}
The pattern across all four walls is identical: if the circle penetrates a boundary, snap its position back inside the bounds, flip the sign of its velocity along that axis, and multiply by bounciness. A bounciness value of 0.6 retains 60% of the normal velocity upon impact โ gradually dissipating kinetic energy like a real basketball.
If you skip snapping the position back inside the boundary, you will run into a notorious physics bug: the ball gets stuck inside the floor, vibrating uncontrollably. Why? On the next frame, the ball is still technically submerged inside the boundary, so the engine reverses velocity again, flipping back and forth infinitely.
The golden rule of game physics: always resolve geometry before resolving velocity.
Body-to-Body Collisions: Impulse Resolution
Now comes the centerpiece. Resolving a collision between two moving circles breaks down into two questions: did they collide? and what happens next?
The first question is answered in one line: if the distance between their centers is less than the sum of their radii, they are intersecting. The second question is the most crucial part of any physics engine: calculating the impulse (instantaneous force applied over time):
// src/engine/world.ts โ World collision resolver
private collideBodies(a: Body, b: Body) {
const totalInvMass = a.invMass + b.invMass;
if (totalInvMass === 0) return; // Two static bodies never collide
const delta = sub(b.pos, a.pos);
const dist = length(delta);
const minDist = a.radius + b.radius;
if (dist >= minDist || dist === 0) return; // No intersection
const normal = normalize(delta); // Unit normal from a to b
const relVel = sub(b.vel, a.vel);
const approach = dot(relVel, normal); // Closing speed on normal
if (approach > 0) return; // Already separating
this.emitContact(a, b, -approach);
// Impulse: resolves impact intensity into a single scalar
const e = Math.min(a.bounciness, b.bounciness);
const impulse = (-(1 + e) * approach) / totalInvMass;
a.vel = sub(a.vel, scale(normal, impulse * a.invMass));
b.vel = add(b.vel, scale(normal, impulse * b.invMass));
// Positional correction: separate by inverse mass ratio
const overlap = minDist - dist;
a.pos = sub(a.pos, scale(normal, overlap * (a.invMass / totalInvMass)));
b.pos = add(b.pos, scale(normal, overlap * (b.invMass / totalInvMass)));
}
Let's unpack these twenty lines, because they constitute the mathematical core of nearly every modern 2D physics engine:
-
normal: The unit vector pointing from the center of bodyato bodyb. It defines the axis along which momentum must transfer. -
approach: The dot product in its prime role. It calculates the relative velocity of the two bodies projected along the collision normal. If positive, the bodies are already moving apart; resolving them would cause them to unnaturally stick together. If negative, they are closing in on each other. -
impulse: The scalar magnitude of the collision force. The factor(1 + e)incorporates the restitution (elasticity) of the bounce. Dividing bytotalInvMassdistributes the reaction force according to each body's weight. A massive body (small invMass) barely budges; a light body (large invMass) gets flung across the screen; and an immovable static body (invMass = 0) stays locked in space. One clean formula, three distinct physical behaviors. - Positional Correction: Just like the floor collision, we push overlapping circles apart immediately along the normal vector, proportional to their inverse mass.
-
emitContact: The physics engine's boundary hook to the outside world. It publishes an event stating: "These two bodies collided with this exact impact speed."
Game mechanics โ shattering wooden crates, dealing impact damage, triggering particle bursts โ do not belong inside the physics solver. They belong in contact event listeners. The engine calculates the physics; the game rules decide what the physics means.

Slingshot launch geometry: dragging backward from the anchor computes an opposite launch velocity scaled by pull distance.
The Slingshot: Impulse Under Your Fingertip
Our simulation is functional. Now we turn it into a game: grab the projectile, drag backwards, and release. The core mechanic that powered Angry Birds.
The concept is straightforward: applying velocity in the exact opposite direction of the drag vector. The farther you pull, the faster the projectile launches:
// src/main.ts
canvas.addEventListener("pointerdown", (e) => {
const p = toWorld(e);
if (length(sub(p, ball.pos)) < ball.radius * 2.5) {
dragging = true;
dragPoint = p;
ball.vel = vec(); // Freeze physics while aiming
}
});
// Note: move and up events are registered on the window object.
// If the player drags outside the canvas boundary, the release is never lost.
// (Listening only on canvas causes slingshots to get stuck when releasing outside.)
window.addEventListener("pointermove", (e) => {
if (dragging) dragPoint = toWorld(e);
});
window.addEventListener("pointerup", () => {
if (!dragging) return;
dragging = false;
const pull = sub(ball.pos, dragPoint); // Opposite of drag = launch vector
ball.vel = scale(pull, LAUNCH_POWER);
});
That comment about window listeners comes from a real bug I hit while testing: registering pointerup strictly on the <canvas> element meant that whenever a player dragged their finger just one pixel beyond the canvas edge and released, the slingshot stayed permanently drawn. Rule of thumb for web gestures: bind initiation to the element, but bind drag updates and release to window.
During the drag interaction, we render a taut elastic line between the projectile and the cursor. Visual feedback gives the player immediate intuition over the launch power they are storing up.

The finished Rescue Operation mini-game in HTML5 Canvas: shatter high-threshold stone blocks to free the central pink orb.
The Game: Rescue Operation
Let's wire the components into a complete mini-game: a pink orb is trapped at the center of the screen, surrounded by a ring of protective stone blocks. You pull back the black projectile using the slingshot, shatter the defensive ring, and free the trapped target.
To keep it engaging, we add a design twist: stones only shatter under high-speed impacts. A sluggish shot merely bounces off harmlessly. Every launch becomes a tactical choice: do you risk a direct precision strike, or bank off the side walls for a ricochet?
Setup takes only a few lines. To ensure consistent behavior across different screen sizes, we normalize all dimensions against the viewport's shorter dimension:
// src/main.ts
// Responsive scaling: normalize dimensions against a 600px reference
let W = window.innerWidth;
let H = window.innerHeight;
const SCALE = Math.min(W, H) / 600;
const world = new World(W, H, 900 * SCALE);
const ball = world.add(
createBody(W * 0.2, H * 0.75, 26 * SCALE, { bounciness: 0.7 }),
);
const pink = world.add(createBody(W / 2, H / 2, 22 * SCALE, { static: true }));
// Ring of protective stones
const stones = new Set<Body>();
const STONES = 10;
for (let i = 0; i < STONES; i++) {
const angle = (i / STONES) * Math.PI * 2;
const stone = createBody(
W / 2 + Math.cos(angle) * 90 * SCALE,
H / 2 + Math.sin(angle) * 90 * SCALE,
20 * SCALE,
{ static: true, bounciness: 0.5 },
);
world.add(stone);
stones.add(stone);
}
Notice 900 * SCALE. Working with pixel dimensions means that 900 px/sยฒ on a compact smartphone display feels radically heavier than on an ultra-wide desktop monitor. Tying dimensions to a unified scale factor preserves identical gameplay physics across mobile and desktop. To keep those window.innerWidth Canvas coordinates razor-sharp on HiDPI screens without distorting physics space, check out Part 2: Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes.
And the gameplay rules live cleanly inside our contact listener:
// src/main.ts โ gameplay mechanics
const BREAK_SPEED = 400 * SCALE; // px/s โ slower impacts won't shatter stones
world.onContact(({ a, b, speed }) => {
const other = a === ball ? b : b === ball ? a : null;
if (!other) return;
if (stones.has(other) && speed > BREAK_SPEED) {
world.remove(other);
stones.delete(other);
spawnParticles(other.pos);
}
if (other === pink) {
world.remove(pink);
won = true; // RESCUED!
}
});
The speed parameter passed to our listener is the exact approach velocity computed by the impulse solver. By exposing that value through an event payload, gameplay design opens up: break thresholds, particle counts, and sound volume fall naturally into place.
The entire physics engine is ~145 lines. The game logic is ~210 lines. And every single bounce on the screen is fully transparent.
What About Production? Returning to Matter.js
Let's be completely candid. We learned how to drive a manual transmission โ but should you build your own transmission every time you build a car?
No.
Our custom engine is deliberately limited to circles. Adding oriented bounding boxes, rotational inertia, friction tensors, broad-phase spatial culling, and constraint joints will easily balloon a custom codebase by thousands of lines. Mature engines like Matter.js and Box2D have battle-tested these edge cases over decades. Rebuilding them is brilliant for learning; rebuilding them for a production deadline is waste.
The great news: because you built this engine, Matter.js is no longer a cryptic black box. Here is the exact same slingshot setup expressed in Matter.js:
// src/matter-demo.ts โ Matter.js equivalent
import Matter from "matter-js";
const engine = Matter.Engine.create();
engine.gravity.y = 1;
const ball = Matter.Bodies.circle(W * 0.2, H * 0.75, 26 * SCALE, {
restitution: 0.7,
});
const pink = Matter.Bodies.circle(W / 2, H / 2, 22 * SCALE, { isStatic: true });
// Thick boundary walls (200px): prevents high-speed tunneling
const walls = [
Matter.Bodies.rectangle(W / 2, -100, 10000, 200, { isStatic: true }),
Matter.Bodies.rectangle(W / 2, H + 100, 10000, 200, { isStatic: true }),
Matter.Bodies.rectangle(-100, H / 2, 200, 10000, { isStatic: true }),
Matter.Bodies.rectangle(W + 100, H / 2, 200, 10000, { isStatic: true }),
];
Matter.Composite.add(engine.world, [ball, pink, ...walls]);
Matter.Events.on(engine, "collisionStart", (event) => {
for (const pair of event.pairs) {
// pair.collision.normal -> our "normal"
// pair.collision.depth -> our "overlap"
}
});
Look familiar?
restitution is our bounciness, isStatic is our invMass = 0, and collisionStart is our onContact. The terminology changed; the underlying physics concepts are identical. The black box is now made of clear glass.
Notice the thick 200px boundary walls in the Matter.js snippet. During my initial Matter.js port, I made the boundary rectangles 20 pixels thin. On a maximum-power slingshot launch, the ball tunneled right through the wall and vanished offscreen. This is tunneling: a high-speed body moves past the boundary in a single frame, so a discrete collision test never detects an intersection.
In our custom engine, walls were handled as strict geometric boundaries (pos.x = radius), making tunneling impossible. In Matter.js, walls are standard rectangular bodies subject to discrete time-step testing. Two distinct architectural designs for the same problem โ and because you wrote an engine from scratch, you recognize the trade-off by instinct rather than getting stranded in GitHub issues.
Architecture Decision Matrix
- Custom Micro-Engine: Educational experiments, hyper-targeted mini-games with simple mechanics (bouncing balls, breakout clones), or ultra-lightweight web widgets where zero bundle footprint is mandatory.
- Matter.js: Polygons, rotation, stacking boxes, springs, constraints, and fast prototyping for production 2D web games.
- Box2D / Rapier (WASM): Performance-critical simulations, high object counts, or authoritative game servers requiring deterministic physics across platforms.
Summary
-
Game Loop: Drive simulation with
requestAnimationFrameanddt; define all speeds per second, never per frame. -
Euler Integration: Gravity is two lines:
velocity += gravity * dtandposition += velocity * dt. -
Inverse Mass: Store
1 / massso static, immovable obstacles cost zero conditional branches in your solver. -
Two-Step Collision: First detect overlap (
dist < r1 + r2), then calculate the impulse response along the collision normal. - Geometry First, Velocity Second: Always resolve physical intersection before adjusting velocities to prevent jittering.
- Decoupled Architecture: Game logic belongs in contact events, never inside the physics integration loop.
- Pragmatic Production: Understand the mechanics by building it once, then use battle-tested libraries like Matter.js or Rapier in production.
๐ Canvas 2D & Game Architecture Series
๐บ๏ธ Series Roadmap: Follow the full browser rendering and physics architecture arc from vector math to deterministic loops.
- Part 1 (You are here): How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas
- Part 2: Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes โ Solving HiDPI rendering blurriness without distorting physics coordinates.
- Part 3: Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript โ Taming variable delta time to make simulation physics completely deterministic across 60Hz and 144Hz monitors.
- Up Next: Broad-Phase Collision & Spatial Hashing (O(nยฒ) -> O(n)) โ Scaling collision detection from 200 to 20,000 objects with spatial grid partitioning.
Source Code & Playable Demo
The complete source code โ including the custom engine, playable game, automated tests, and Matter.js comparison โ is open-source on GitHub:
๐ฆ GitHub Repository: github.com/m2-md/canvas-physics-from-scratch
๐ฎ Playable Live Demo: m2-md.github.io/canvas-physics-from-scratch
Building this project reminded me of an interesting reality: much of the intimidation surrounding the term "physics engine" is created by the tooling itself. When you peel back the layers, you find high-school math and twenty lines of vector projections. Many concepts we label "too hard" in software engineering are like that โ the box is simply larger than the engine inside it.
Pull back the slingshot and smash the stones. The pink orb is waiting. โ๏ธ๐ง
๐ About the Author
I'm Mustafa Morbel, a senior software engineer and architect with over 17 years of experience building scalable web applications, interactive browser graphics, and AI-assisted engineering workflows.
You can inspect all codebases, runnable demos, and test suites across my GitHub profile.
For new technical guides and architectural deep dives, feel free to connect on LinkedIn and X / Twitter (@mustafamorbel).
Have you ever written a custom physics loop for a web project, or do you reach straight for Matter.js and Rapier? I'd love to hear your thoughts in the comments ๐ง ๐ฌ
๐ฆ Want the Bundled Starter Kit & Cheatsheets?
If you want all 3 TypeScript engines, HiDPI helpers, fixed-timestep loop templates, and vector physics cheatsheets in one clean zip, grab the TS 2D Canvas Physics & HiDPI Starter Kit (or unlock all kits free with a Buy Me a Coffee membership).

Top comments (0)