<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Mustafa Morbel]]></title><description><![CDATA[Mustafa Morbel]]></description><link>https://mkare.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 21 Nov 2026 19:35:48 GMT</lastBuildDate><atom:link href="https://mkare.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Shaking Hands with Everyone: Broad-Phase Collision and Spatial Hashing from 200 to 20,000 Bodies]]></title><description><![CDATA[Cut O(n²) collision checks from 199.99M pairs to 14,323 candidates at 20,000 bodies with a TypeScript spatial hash grid.]]></description><link>https://mkare.hashnode.dev/shaking-hands-with-everyone-broad-phase-collision-and-spatial-hashing-from-200-to-20-000-bodies</link><guid isPermaLink="true">https://mkare.hashnode.dev/shaking-hands-with-everyone-broad-phase-collision-and-spatial-hashing-from-200-to-20-000-bodies</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[Game Development]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Fri, 20 Nov 2026 19:18:22 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium.</em> <a href="https://medium.com/@mkare/shaking-hands-with-everyone-broad-phase-collision-and-spatial-hashing-from-200-to-20-000-bodies-a5d1628b85a2?sk=029ce9604f262a1350dc835d2b899eb3"><em>Read on Medium for free via Friend Link</em></a><em>.</em></p>
<p>🎮 <a href="https://m2-md.github.io/broad-phase-collision-spatial-hash/"><strong>Try the Live Interactive Demo</strong></a> · 📦 <a href="https://github.com/m2-md/broad-phase-collision-spatial-hash"><strong>GitHub Repo &amp; Vitest Suite</strong></a> · ⚡ <a href="https://www.buymeacoffee.com/mkare/e/599265"><strong>Get the TS 2D Canvas Physics Starter Kit</strong></a></p>
</blockquote>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*CUuAW1HENpWCY4rk66MGvA.png" alt="Illustration of a broad-phase bouncer at a neon narrow-phase nightclub entrance, letting 14,323 candidate pairs inside while turning away rejected circle pairs." style="display:block;margin:0 auto" />

<p><em>Broad-phase acts as a bouncer in front of narrow-phase: out of 199.99M pairs at 20,000 bodies, only 14,323 candidates make it inside.</em></p>
<h2>Quick takeaways</h2>
<ul>
<li>Checking every pair produces <code>n(n - 1) / 2</code> tests: 199,990,000 checks at 20,000 bodies, dropping the browser demo to 1 FPS at 2,500 bodies.</li>
<li>A cheap spatial hash grid filters impossible pairs first, leaving <code>collideBodies</code> (narrow-phase) completely untouched.</li>
<li>On 20,000 uniformly distributed bodies, candidate pairs drop from 199,990,000 to 14,323 (nearly 14,000× fewer checks), lifting 2,500-body FPS from 1 to 46.</li>
<li>A deterministic Vitest parity suite verifies zero missed collisions against brute-force O(n²) overlap checks, alongside a benchmark against a QuadTree.</li>
</ul>
<p>The physics engine was done, the game ran smoothly, and I was happily pulling back the slingshot to smash blocks. Then curiosity hit: “What if this scene had two hundred bodies instead of twenty?”</p>
<p>I dumped two hundred balls onto the canvas. The frame rate noticeably dipped.</p>
<p>I added a thousand. The page froze, the cooling fan kicked in, and my laptop started humming like a jet preparing for takeoff. Rendering was relaxed because drawing a thousand circles is trivial for a browser; the bottleneck was that nested loop running every frame.</p>
<p>When we previously <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">built a 2D physics engine from scratch in Canvas</a>, we solved collisions the brute-force way: comparing every body against every other body. Back then, I admitted it didn’t scale and punted broad-phase optimization to Matter.js. Today, we pay off that debt by building our own broad-phase from scratch and scaling the engine from 200 bodies to 20,000 without touching Matter.js.</p>
<p>Think of it like a wedding reception. Right now, our engine insists that every guest walk across the hall and shake hands with every other guest one by one. Charming at a table of twenty; a disaster in a hall of two thousand. Instead of letting guests roam the whole hall, we seat them at tables and have everyone shake hands only with their tablemates.</p>
<h2>The O(n²) wall</h2>
<p>Measuring the loop puts a number on why it slows down. Our engine’s <code>step()</code> function ended with these three lines:</p>
<pre><code class="language-ts">// BEFORE — legacy version of the physics engine; NOT in this repo, replaced by broad-phase
// 3. Body-body collisions (every pair once)
for (let i = 0; i &lt; this.bodies.length; i++) {
  for (let j = i + 1; j &lt; this.bodies.length; j++) {
    this.collideBodies(this.bodies[i], this.bodies[j]);
  }
}
</code></pre>
<p>It looks harmless. Yet for <code>n</code> bodies, this nested loop generates <code>n × (n - 1) / 2</code> pairs. That is our handshake count: everyone in the room shakes everyone else's hand once.</p>
<p>The math is merciless. At 200 bodies, that is 19,900 checks, which is manageable. At 2,000 bodies, 1,999,000 checks. At 20,000 bodies, 199,990,000 checks. Multiplying the object count by 100 multiplies the workload by 10,000×. Broad-phase exists to avoid that quadratic growth.</p>
<img src="https://miro.medium.com/v2/1*E4qrStQK2dEsO05uvKszVQ.png" alt="Vintage train-station split-flap board displaying O(n²) pair counts using n(n-1)/2: 200 to 19,900, 2,000 to 1,999,000, and 20,000 to 199,990,000 handshakes." style="display:block;margin:0 auto" />

<p><em>Quadratic pair growth under n(n - 1) / 2: scaling 10× in bodies multiplies naive collision checks by 100×.</em></p>
<p>We don’t need a heavy profiler to plot this curve. We can count the exact number of checks directly, giving us a deterministic metric that never varies from machine to machine:</p>
<pre><code class="language-ts">// src/benchmark.ts
export function countNaiveChecks(n: number): number {
  let checks = 0;
  for (let i = 0; i &lt; n; i++) {
    for (let j = i + 1; j &lt; n; j++) {
      checks++; // real collideBodies would run here
    }
  }
  return checks;
}
</code></pre>
<p>To feel the drop live in the browser, a lightweight frame counter is enough, with no HUD library required:</p>
<pre><code class="language-ts">// src/demo.ts
let frames = 0;
let fpsSince = performance.now();
let fps = 0;
 
function sampleFps(now: number) {
  frames++;
  if (now - fpsSince &gt;= 500) {
    fps = Math.round((frames * 1000) / (now - fpsSince));
    frames = 0;
    fpsSince = now;
  }
}
</code></pre>
<p>Putting a “+500 bodies” button on screen and watching FPS melt with every click is the most convincing moment in this whole exercise. The chart doesn’t slope gently downward; past a threshold, O(n²) makes it fall off a cliff.</p>
<img src="https://miro.medium.com/v2/1*OkFF97z4p6W_bLoGTh-DeQ.png" alt="Industrial control panel showing a finger pressing a red +500 button while an analog FPS gauge drops through 60, 22, to FREEZE under an O(n²) warning light." style="display:block;margin:0 auto" />

<p><em>Every +500 bodies click compounds O(n²) checks until frame rate drops off a cliff.</em></p>
<h2>Broad-phase vs. narrow-phase</h2>
<p>Take another look at <code>collideBodies</code> from our engine:</p>
<pre><code class="language-ts">// src/world.ts — EXCERPT: see file for full body
private collideBodies(a: Body, b: Body) {
  const totalInvMass = a.invMass + b.invMass;
  if (totalInvMass === 0) return; // two static bodies cannot collide
 
  const delta = sub(b.pos, a.pos);
  const dist = length(delta);
  const minDist = a.radius + b.radius;
  if (dist &gt;= minDist || dist === 0) return; // no contact
  // ... normal, impulse, overlap correction ...
}
</code></pre>
<p>This function determines with exact precision whether two bodies <em>actually</em> collide, then resolves the impact with impulses. It is accurate and expensive because it runs square roots, vector subtractions, and dot products.</p>
<p>This stage is called narrow-phase, because it zooms in on a single candidate pair and decides its fate with full geometric precision. Every physics engine splits its collision pipeline into two stages:</p>
<ul>
<li>Broad-phase is cheap and coarse. It answers “could these two bodies <em>possibly</em> be colliding?” using a handful of additions and comparisons, eliminating millions of impossible pairs in one sweep and leaving a small list of candidate pairs. It never claims two bodies definitely collided, only that they are worth checking.</li>
<li>Narrow-phase is expensive and exact. It runs <em>only</em> on the candidate pairs produced by broad-phase, tests true geometry, and resolves impulses. Our <code>collideBodies</code> is already the narrow-phase.</li>
</ul>
<p>Our engine’s only crime was skipping broad-phase altogether. That naive nested loop shoved <em>every</em> pair straight into the expensive narrow-phase. We were forcing the entire reception hall to shake hands.</p>
<p>The target pipeline is simple:</p>
<pre><code class="language-ts">every frame:
  1. integration (gravity → velocity → position)  ← unchanged
  2. wall collisions                              ← unchanged
  3. BROAD-PHASE  → generate candidate pairs      ← NEW
  4. NARROW-PHASE → collideBodies(a, b)           ← fewer calls
</code></pre>
<p>Notice what didn’t change: we don’t touch a single line inside narrow-phase. <code>collideBodies</code> stays exactly as it is. All we do is place a bouncer in front of it: a spatial hash grid.</p>
<h2>A uniform spatial hash grid</h2>
<p>The bouncer’s job is straightforward: divide the world into equal square cells, place each body into the cell(s) it occupies, and suggest candidate pairs only from bodies sharing the same cell. We split the hall into tables; now you only shake hands with your tablemates.</p>
<p>This data structure is called a spatial hash grid. The “hash” comes from mapping a body’s world coordinates <code>(x, y)</code> to a cell key that points into a <code>Map</code> holding the list of bodies in that cell.</p>
<p>First, we define the minimal shape the grid needs to see. The grid doesn’t care about a body’s mass, velocity, or restitution, only <em>where</em> it is and <em>how wide</em> it is:</p>
<pre><code class="language-ts">// src/grid.ts
import type { Vec2 } from "./vec";
 
// Anything insertable into the grid: just a position and a radius.
export interface HasBounds {
  pos: Vec2;
  radius: number;
}
</code></pre>
<p>Our <code>Body</code> type already satisfies this (<code>pos</code> and <code>radius</code>), so the grid plugs directly into our engine. Now the class skeleton:</p>
<pre><code class="language-ts">// src/grid.ts — class skeleton; insert/queryPairs follow below
export class SpatialHashGrid&lt;T extends HasBounds&gt; {
  private cells = new Map&lt;string, number[]&gt;(); // cell key → body indices in that cell
  private items: T[] = [];                      // index → body
 
  constructor(public readonly cellSize: number) {}
 
  // Start each frame fresh by clearing previous cells.
  clear(): void {
    this.cells.clear();
    this.items.length = 0;
  }
 
  // Convert a cell coordinate pair into a Map key.
  private hash(cx: number, cy: number): string {
    return cx + "," + cy;
  }
 
  // Snap a world coordinate down to its cell coordinate.
  private cellOf(v: number): number {
    return Math.floor(v / this.cellSize);
  }
}
</code></pre>
<p>I used a string key like <code>"3,-2"</code>. Yes, string keys in a performance article look slightly ironic, and there is a reason for it: first make it right, then make it fast.</p>
<p>The <code>hash</code> function must map two cell coordinates to a <em>collision-free</em> key. Many spatial hash tutorials use an XOR hash like <code>cx * prime1 ^ cy * prime2</code>. That approach has a subtle flaw: two distinct cells can collide onto the same hash bucket, silently merging two separate tables into one and spawning phantom candidate pairs. A string key eliminates hash collisions completely and handles negative coordinates without extra math. It raises the constant factor slightly, which is a grain of sand next to the quadratic wall.</p>
<img src="https://miro.medium.com/v2/1*ccemIQks2_wwb-95kSokLg.png" alt="Vintage hotel key rack with brass tags labeled 3,-2, 3,-1, 4,-2, and 4,-1 alongside a crossed-out XOR symbol, illustrating collision-free string cell keys in a spatial hash grid." style="display:block;margin:0 auto" />

<p><em>Using "\({cx},\){cy}" string keys in a Map avoids XOR hash collisions—collision-free, slightly ironic.</em></p>
<h2>Insertion, querying, and cell size</h2>
<p>Next come insertion and querying. Insertion has one subtlety: if we insert a body only into the cell containing its center, two circles straddling a cell boundary will overlap in world space while sitting at different tables, never seeing each other. Missed collisions are the sneakiest bugs in physics; you rarely notice them until a body tunnels straight through a corner.</p>
<p>The fix is clean: insert the body into <em>every cell touched by its AABB</em> (axis-aligned bounding box). A small circle usually lands in one cell; a circle straddling a boundary gets written to two or four cells and reliably meets its neighbor:</p>
<pre><code class="language-ts">// src/grid.ts — SpatialHashGrid body
insert(item: T): void {
  const id = this.items.length;
  this.items.push(item);
 
  const minCx = this.cellOf(item.pos.x - item.radius);
  const maxCx = this.cellOf(item.pos.x + item.radius);
  const minCy = this.cellOf(item.pos.y - item.radius);
  const maxCy = this.cellOf(item.pos.y + item.radius);
 
  for (let cx = minCx; cx &lt;= maxCx; cx++) {
    for (let cy = minCy; cy &lt;= maxCy; cy++) {
      const key = this.hash(cx, cy);
      let cell = this.cells.get(key);
      if (!cell) {
        cell = [];
        this.cells.set(key, cell);
      }
      cell.push(id);
    }
  }
}
</code></pre>
<p>On the query side, we pair up every body inside each cell. However, inserting via AABB introduces a cost: if two bodies share <em>two</em> cells, they will be emitted twice. That is double counting, and it wastes narrow-phase work. The fix is deduplicating with a single integer key ordered by ID:</p>
<pre><code class="language-ts">// src/grid.ts — SpatialHashGrid body
queryPairs(): Array&lt;[T, T]&gt; {
  const pairs: Array&lt;[T, T]&gt; = [];
  const seen = new Set&lt;number&gt;();
  const n = this.items.length;
 
  for (const cell of this.cells.values()) {
    for (let i = 0; i &lt; cell.length; i++) {
      for (let j = i + 1; j &lt; cell.length; j++) {
        const a = cell[i];
        const b = cell[j];
        // low id * N + high id → unique, collision-free key per pair.
        const lo = a &lt; b ? a : b;
        const hi = a &lt; b ? b : a;
        const key = lo * n + hi;
        if (seen.has(key)) continue;
        seen.add(key);
        pairs.push([this.items[lo], this.items[hi]]);
      }
    }
  }
  return pairs;
}
</code></pre>
<p>The <code>lo * n + hi</code> trick packs two IDs into a single integer. Because <code>n</code> is the total number of bodies, this key is guaranteed collision-free: every ordered pair maps to a unique number, and the <code>seen</code> set skips any pair it has already encountered.</p>
<p>The single parameter that decides how well the grid performs is cell size. The first time I wrote a spatial grid, I made the cells huge, basically one giant cell covering the whole world. I wired up the grid, hit run, and FPS didn’t budge a single frame. I stared at the screen for half an hour wondering why it wasn’t faster. The reason was embarrassingly simple: one giant cell puts everyone back at a single table. Too large, and the grid becomes an expensive imitation of the naive loop. Too small, and every body spills into dozens of cells, blowing up insertion cost.</p>
<p>The sweet spot usually sits around a cell size of 1 to 2× the largest body’s diameter. At that ratio, each body lands in a handful of cells, and each cell holds a handful of bodies. Instead of guessing, we can run a small sweep over cell sizes and count the generated candidate pairs:</p>
<pre><code class="language-ts">// src/benchmark.ts
export function sweepCellSize(items: HasBounds[], sizes: number[]) {
  return sizes.map((cellSize) =&gt; {
    const grid = new SpatialHashGrid&lt;HasBounds&gt;(cellSize);
    for (const it of items) grid.insert(it);
    const candidates = grid.queryPairs().length;
    return { cellSize, candidates };
  });
}
</code></pre>
<p>Candidate count moves in one direction: larger cells produce more candidates. In a scene with <code>n = 2,000</code> and <code>seed = 1</code>, cell size <code>8</code> yields <code>638</code> candidates, <code>24</code> yields <code>1,418</code>, <code>48</code> yields <code>3,162</code>, and a world-sized cell yields <code>1,999,000</code> (the exact naive count). Smaller cells shrink candidate count, yet each body gets written into more cells, increasing insertion overhead. Total time spent across insertion, query, and narrow-phase traces a U-curve, and the bottom of that U-curve is the right cell size for your scene. Measure to find it rather than relying on a formula.</p>
<img src="https://miro.medium.com/v2/1*b2OuCdbcyksKWQdSSK8P4Q.png" alt="Science-fair tri-fold board titled Measure Cell Size, Don’t Guess, showing a U-shaped performance curve against cellSize and a wire grid holding spheres." style="display:block;margin:0 auto" />

<p><em>Benchmarking cellSize reveals the sweet spot: too small bloats insertion, too large bloats narrow-phase—measure, don't guess.</em></p>
<h2>Large and fast bodies</h2>
<p>Uniform grids have one famous weakness: a single giant body. Picture a guest in the hall whose arms span three tables at once. Because we insert by AABB, that giant gets written into <em>every</em> cell it overlaps. It won’t miss anyone, but if it touches half the cells in the world, comparison counts climb right back up. A uniform grid shines when bodies are roughly similar in size; if an ant and an elephant share the same scene, no single cell size fits both.</p>
<p>At small scales you can ignore this. When density spikes in one corner of the hall and drops to zero everywhere else, a one-size-fits-all cell stops working, and a QuadTree handles it better.</p>
<img src="https://miro.medium.com/v2/1*hmmXr_kEcSp2qTYr_YYG2Q.png" alt="Museum display case showing a large elephant spanning multiple grid cells next to a tiny ant inside a single cell, illustrating the limits of a uniform grid with fixed cellSize = 48." style="display:block;margin:0 auto" />

<p><em>When an ant and an elephant share a uniform grid, no single cellSize fits both—the classic case for a QuadTree.</em></p>
<p>Then there is the fast-body problem. If your bullet travels half the screen in a single frame, <code>insert</code> only places it in the cells of its <em>current</em> position, completely blind to bodies along the corridor it just crossed. Broad-phase alone cannot solve tunneling, but it can at least surface the right candidates: insert the body using the swept AABB covering both its current position and its next-frame position:</p>
<pre><code class="language-ts">// src/grid.ts — SpatialHashGrid body
insertSwept(item: T &amp; { vel: Vec2 }, dt: number): void {
  const nx = item.pos.x + item.vel.x * dt; // next-frame position
  const ny = item.pos.y + item.vel.y * dt;
 
  const minX = Math.min(item.pos.x, nx) - item.radius;
  const maxX = Math.max(item.pos.x, nx) + item.radius;
  const minY = Math.min(item.pos.y, ny) - item.radius;
  const maxY = Math.max(item.pos.y, ny) + item.radius;
 
  const id = this.items.length;
  this.items.push(item);
  for (let cx = this.cellOf(minX); cx &lt;= this.cellOf(maxX); cx++) {
    for (let cy = this.cellOf(minY); cy &lt;= this.cellOf(maxY); cy++) {
      const key = this.hash(cx, cy);
      let cell = this.cells.get(key);
      if (!cell) {
        cell = [];
        this.cells.set(key, cell);
      }
      cell.push(id);
    }
  }
}
</code></pre>
<p>Our <code>Body</code> already carries <code>vel</code>, so this works out of the box. Keep in mind that this introduces the bullet to the right candidates without resolving the collision itself. Stopping a bullet from teleporting through a wall belongs to narrow-phase (continuous collision detection and swept intersection tests). Broad-phase only proposes candidates; it doesn't make final decisions.</p>
<h2>Wiring it into the engine: broad to narrow</h2>
<p>Now we can rip that naive nested loop out of <code>step()</code> and drop in the two-stage pipeline. We add a grid field to <code>World</code> and replace the final block (running inside a <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11">fixed-timestep game loop</a> for deterministic physics):</p>
<pre><code class="language-ts">// src/world.ts — relevant excerpt (gravity, constructor, and collideWalls are in the file)
export class World {
  bodies: Body[] = [];
  grid = new SpatialHashGrid&lt;Body&gt;(48); // cell ≈ 1–2× largest diameter
 
  step(dt: number) {
    // 1. Integration (unchanged)
    for (const b of this.bodies) {
      if (b.invMass === 0) continue;
      b.vel = add(b.vel, scale(this.gravity, dt));
      b.pos = add(b.pos, scale(b.vel, dt));
    }
 
    // 2. Wall collisions (unchanged)
    for (const b of this.bodies) this.collideWalls(b);
 
    // 3. BROAD-PHASE: clear and populate the grid each frame
    this.grid.clear();
    for (const b of this.bodies) this.grid.insert(b);
 
    // 4. NARROW-PHASE: run existing solver only on candidate pairs
    for (const [a, b] of this.grid.queryPairs()) {
      this.collideBodies(a, b);
    }
  }
}
</code></pre>
<p>Look at what we did to narrow-phase: nothing. <code>collideBodies</code> sits untouched, identical line for line to the original physics engine. All we did was shrink the stream of pairs reaching it from millions down to thousands. Broad-phase works simply by calling the expensive function less often.</p>
<p>One detail worth noting: we <code>clear()</code> and rebuild the grid from scratch every frame. Updating bodies incrementally as they move between cells sounds faster, but for most 2D games, rebuilding from scratch is both simpler and fast enough because insertion is already cheap. Measure before optimizing prematurely; you may never need incremental updates.</p>
<h2>Benchmark: grid vs. QuadTree vs. naive</h2>
<p>To weigh all three approaches on the same scale, we need a deterministic scene generator: a seeded PRNG so every run on every machine produces the exact same layout:</p>
<pre><code class="language-ts">// src/benchmark.ts
// mulberry32: small, fast, deterministic PRNG
function makeRng(seed: number): () =&gt; number {
  return () =&gt; {
    seed |= 0;
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed &gt;&gt;&gt; 15), 1 | seed);
    t = (t + Math.imul(t ^ (t &gt;&gt;&gt; 7), 61 | t)) ^ t;
    return ((t ^ (t &gt;&gt;&gt; 14)) &gt;&gt;&gt; 0) / 4294967296;
  };
}
 
// Constant DENSITY: world area scales with body count (no clustering).
export function makeScene(n: number, seed = 1): HasBounds[] {
  const rng = makeRng(seed);
  const world = Math.sqrt(n) * 40; // keep density constant
  const items: HasBounds[] = [];
  for (let i = 0; i &lt; n; i++) {
    items.push({
      pos: { x: rng() * world, y: rng() * world },
      radius: 6,
    });
  }
  return items;
}
</code></pre>
<p>Scaling <code>world</code> with <code>sqrt(n)</code> is intentional: it keeps spatial density constant. That matters because a spatial grid's "near-linear" promise holds under this exact condition. Pile all 20,000 bodies onto a single point, and the grid degrades right back to O(n²), which is just a tax levied by physics. Under heavy clustering, a QuadTree fights back better.</p>
<p>The harness counts how many candidate pairs each method emits, giving us a deterministic, hardware-independent metric showing exactly how many times narrow-phase gets called:</p>
<pre><code class="language-ts">// src/benchmark.ts
export function benchmark(n: number) {
  const scene = makeScene(n);
 
  // Naive: every pair once — closed form n(n-1)/2 (no need to loop 200M times when n is large).
  const naive = (n * (n - 1)) / 2;
 
  // Spatial Hash Grid
  const grid = new SpatialHashGrid&lt;HasBounds&gt;(24);
  for (const it of scene) grid.insert(it);
  const gridPairs = grid.queryPairs().length;
 
  // QuadTree
  const qt = new QuadTree&lt;HasBounds&gt;({ x: 0, y: 0, w: Math.sqrt(n) * 40, h: Math.sqrt(n) * 40 });
  for (const it of scene) qt.insert(it);
  const qtPairs = qt.queryPairs().length;
 
  return { n, naive, gridPairs, qtPairs };
}
</code></pre>
<p>Here are the candidate pair counts from a run (<code>cellSize = 24</code>, constant-density scene, <code>seed = 1</code>; numbers are deterministic and reproducible via <code>npm run bench</code>):</p>
<pre><code class="language-ts">Bodies (n) | Naive Pairs | Grid Candidates | QuadTree Candidates
-----------+-------------+-----------------+--------------------
200        | 19,900      | 160             | 4,451
2,000      | 1,999,000   | 1,418           | 163,493
20,000     | 199,990,000 | 14,323          | 4,818,747
</code></pre>
<p>The naive column climbs quadratically. The grid stays nearly linear: at 20,000 bodies, naive runs 199,990,000 checks while the grid emits just 14,323 candidates, nearly 14,000× less work. The QuadTree also bridges the cliff compared to naive: 4,818,747 instead of 199,990,000, roughly 40× fewer checks. Yet on this uniformly distributed scene, it trails far behind the grid because bodies straddling node boundaries get stuck in upper nodes and pair against everything below them. On uniform, spread-out scenes, the grid wins, turning the FPS cliff into a flat plateau. The browser demo shows the same story: at 2,500 bodies, naive mode collapses to 1 FPS while grid mode holds 46 FPS.</p>
<p>So what is a QuadTree? Instead of slicing the world into fixed cells, it subdivides <em>by occupancy</em>. A region splits into four quadrants when crowded and stays whole when empty. That adaptability directly answers the uniform grid’s “one-size cell” limitation, shining when ants and elephants share the canvas or density varies wildly. Our benchmark runs a real QuadTree; here is its skeleton:</p>
<pre><code class="language-ts">// src/quadtree.ts — skeleton: see file for full subdivide/childFor/collect bodies
interface QuadBounds { x: number; y: number; w: number; h: number; }
 
export class QuadTree&lt;T extends HasBounds&gt; {
  private items: T[] = [];
  private children: QuadTree&lt;T&gt;[] | null = null;
 
  constructor(
    private bounds: QuadBounds,
    private capacity = 8,
    private maxDepth = 8,
    private depth = 0,
  ) {}
 
  insert(item: T): void {
    if (this.children) {
      const c = this.childFor(item);
      if (c) {
        c.insert(item);
        return;
      } // fits completely inside one child
    }
    this.items.push(item);
    if (
      !this.children &amp;&amp;
      this.items.length &gt; this.capacity &amp;&amp;
      this.depth &lt; this.maxDepth
    ) {
      this.subdivide();
    }
  }
 
  // Candidate pairs: each node's own items + pairs with ancestor items.
  queryPairs(): Array&lt;[T, T]&gt; {
    const out: Array&lt;[T, T]&gt; = [];
    this.collect([], out);
    return out;
  }
}
</code></pre>
<p>I won’t unpack every detail here, since QuadTrees deserve their own article (coming up next in this series). For now, the main trade-off is clear: a uniform grid is both faster and simpler when bodies are similarly sized and spread out; a QuadTree pulls ahead on clustered scenes with widely varying object sizes. Neither wins everywhere because the shape of your scene decides. Writing both and measuring on your own workload beats any blog debate.</p>
<blockquote>
<p><em>Author’s note: While writing that follow-up, I spotted an omission in this QuadTree:</em> <code>*collect()*</code> <em>passes the ancestor list down to child nodes without pruning. As a result, large bodies stuck in upper nodes get paired against the entire subtree below them, making the QuadTree column above look worse than it needs to be. Filtering out ancestors whose AABB doesn't touch the child's bounds (a one-line</em> <code>*aabbHitsBounds*</code> <em>check) drops candidates on the exact same scene from 4,818,747 to 155,240, completely losslessly, since</em> <code>*childFor*</code> <em>already requires full containment. I'm keeping the table above as-is because it reflects the honest measurement of this code, so don't write off QuadTrees based on it. The full fix and head-to-head re-benchmark across both scene types are Up Next.</em></p>
</blockquote>
<h2>Tests: does the grid ever lie?</h2>
<p>Broad-phase has only one unforgivable sin: <em>missing</em> a real collision. Emitting extra false candidates is forgivable; narrow-phase filters them out, costing only a bit of CPU. If the grid fails to pair two overlapping bodies, however, that collision vanishes silently, a body ghosts through a wall, and players scream “bug.”</p>
<p>So the real invariant to test is simple: the grid’s candidates must cover every truly overlapping pair. The cleanest way to prove this is comparing the grid’s filtered output against brute-force O(n²). First, a pure, deterministic overlap check for two circles:</p>
<pre><code class="language-ts">// src/overlap.ts
export function circlesOverlap(a: HasBounds, b: HasBounds): boolean {
  const dx = a.pos.x - b.pos.x;
  const dy = a.pos.y - b.pos.y;
  const r = a.radius + b.radius;
  return dx * dx + dy * dy &lt; r * r; // no sqrt — squared distance is enough
}
</code></pre>
<p>We tag test bodies with an <code>id</code>, filter the grid's candidate pairs by actual overlap, and assert an exact match against brute-force:</p>
<pre><code class="language-ts">// test/grid.test.ts — SpatialHashGrid suite
// (the file also includes a QuadTree parity test: 4 tests total)
import { describe, it, expect } from "vitest";
import { SpatialHashGrid, type HasBounds } from "../src/grid";
import { circlesOverlap } from "../src/overlap";
 
interface TestItem extends HasBounds { id: number; }
 
function scene(n: number, seed: number): TestItem[] {
  let s = seed;
  const rand = () =&gt; {
    s = (s * 1103515245 + 12345) &amp; 0x7fffffff;
    return s / 0x7fffffff;
  };
  return Array.from({ length: n }, (_, id) =&gt; ({
    id,
    pos: { x: rand() * 400, y: rand() * 400 },
    radius: 6 + rand() * 10, // varying radii: stress multi-cell AABB insertion
  }));
}
 
// Brute-force: all truly overlapping pairs (ground truth)
function bruteForceOverlaps(items: TestItem[]): Set&lt;string&gt; {
  const set = new Set&lt;string&gt;();
  for (let i = 0; i &lt; items.length; i++) {
    for (let j = i + 1; j &lt; items.length; j++) {
      if (circlesOverlap(items[i], items[j])) set.add(`${i}-${j}`);
    }
  }
  return set;
}
 
describe("SpatialHashGrid.queryPairs", () =&gt; {
  it("never misses a truly overlapping pair (matches brute-force)", () =&gt; {
    const items = scene(500, 42);
    const grid = new SpatialHashGrid&lt;TestItem&gt;(24);
    for (const it of items) grid.insert(it);
 
    const fromGrid = new Set&lt;string&gt;();
    for (const [a, b] of grid.queryPairs()) {
      if (circlesOverlap(a, b)) {
        const [lo, hi] = a.id &lt; b.id ? [a.id, b.id] : [b.id, a.id];
        fromGrid.add(`${lo}-${hi}`);
      }
    }
 
    expect(fromGrid).toEqual(bruteForceOverlaps(items));
  });
 
  it("never emits the same pair twice (no double counting)", () =&gt; {
    const items = scene(300, 7);
    const grid = new SpatialHashGrid&lt;TestItem&gt;(20);
    for (const it of items) grid.insert(it);
 
    const pairs = grid.queryPairs();
    const keys = pairs.map(([a, b]) =&gt;
      a.id &lt; b.id ? `${a.id}-${b.id}` : `${b.id}-${a.id}`,
    );
    expect(new Set(keys).size).toBe(keys.length); // all unique
  });
 
  it("pairs a large body spanning many cells with all its neighbors", () =&gt; {
    const big: TestItem = { id: 0, pos: { x: 100, y: 100 }, radius: 60 };
    const small: TestItem[] = [
      { id: 1, pos: { x: 60, y: 100 }, radius: 5 },
      { id: 2, pos: { x: 140, y: 100 }, radius: 5 },
      { id: 3, pos: { x: 100, y: 55 }, radius: 5 },
    ];
    const grid = new SpatialHashGrid&lt;TestItem&gt;(24); // cell &lt;&lt; large diameter
    for (const it of [big, ...small]) grid.insert(it);
 
    const hits = new Set&lt;number&gt;();
    for (const [a, b] of grid.queryPairs()) {
      if (circlesOverlap(a, b)) {
        if (a.id === 0) hits.add(b.id);
        if (b.id === 0) hits.add(a.id);
      }
    }
    expect(hits).toEqual(new Set([1, 2, 3])); // caught all three
  });
});
</code></pre>
<p>The first test is the heart of the suite: 500 bodies of varying sizes, seeded so every run is identical. The grid’s filtered candidates must match the brute-force overlap set <em>exactly</em>. Missing even a single pair turns the test red. I deliberately varied <code>radius</code> so bodies span multiple cells via their AABB, putting both deduplication and boundary coverage under real pressure.</p>
<p>When this test is green, your broad-phase is trustworthy. You have proven that the bouncer filtering out millions of pairs never turned away a single pair that actually collided. Few green checks in a physics engine feel more reassuring than that.</p>
<h2>Summary</h2>
<ol>
<li>Naive pair-by-pair collision testing is O(n²): multiplying bodies by 100 multiplies work by 10,000, directly from <code>n(n - 1) / 2</code>.</li>
<li>Collision pipelines have two stages: a cheap, coarse broad-phase filters candidates, and an exact, expensive narrow-phase resolves them. <code>collideBodies</code> was narrow-phase from day one.</li>
<li>A spatial hash grid divides the world into equal cells, hashes bodies to cell keys, and pairs only bodies sharing a cell. Split the hall into tables; shake hands only at your table.</li>
<li>Insert each body into <em>every</em> cell touched by its AABB (so boundary collisions are never missed), and deduplicate candidate pairs with an ID-ordered integer key (so pairs are never checked twice).</li>
<li>Set cell size to about 1 to 2× the largest body’s diameter; too large collapses back toward naive, too small explodes insertion cost. Sweep and measure instead of guessing.</li>
<li>Uniform grids excel on spread-out, similarly sized bodies; QuadTrees pull ahead on clustered scenes with widely varying sizes. Let your scene shape pick the winner.</li>
<li>Broad-phase has one unforgivable sin: missing a real collision. Your main test is that filtered candidates must equal the brute-force overlap set.</li>
</ol>
<p>The grid, QuadTree, benchmark harness, live FPS demo, and Vitest suite are all in the <a href="https://github.com/m2-md/broad-phase-collision-spatial-hash">GitHub repository</a>. Run <code>npm test</code> to verify pair parity and <code>npm run dev</code> to watch the FPS cliff disappear, or open the <a href="https://m2-md.github.io/broad-phase-collision-spatial-hash/">interactive live demo</a> right in your browser.</p>
<p>When we first built our physics engine, we brushed broad-phase aside as “production work Matter.js handles.” Saying that out loud made it sound like a massive engineering undertaking; sitting down to write it produced eighty lines around a <code>Map</code> and an integer deduplication trick. Estimating the size of a problem from across the room almost always inflates it.</p>
<p>We split the hall into tables, so twenty thousand guests can dance at once without shaking hands with the wrong person.</p>
<p>How are you handling broad-phase collision culling in your own 2D engine or Canvas projects? I’d love to hear your thoughts.</p>
<h2>Canvas 2D and game architecture series</h2>
<ul>
<li>Part 1: <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas</a></li>
<li>Part 2: <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8">Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes</a></li>
<li>Part 3: <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11">Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript</a></li>
<li>Part 4: <a href="https://medium.com/@mkare/return-the-cart-clear-the-exit-object-pools-and-zero-allocation-loops-in-canvas-4051c97ff8a7">Return the Cart, Clear the Exit: Object Pools and Zero-Allocation Loops in Canvas</a></li>
<li>Part 5: <a href="https://medium.com/@mkare/no-need-to-wipe-the-whole-table-dirty-rectangle-rendering-in-canvas-2d-50de001bf7b1">No Need to Wipe the Whole Table: Dirty Rectangle Rendering in Canvas 2D</a></li>
<li>Part 6 (This Article): Shaking Hands with Everyone: Broad-Phase Collision and Spatial Hashing from 200 to 20,000 Bodies</li>
<li>Up Next (Part 7): <em>Quadtree Collision Culling: Adaptive Spatial Partitioning and Fixing Ancestor Pruning</em></li>
</ul>
<h2>About the author</h2>
<p>I’m Mustafa Morbel, a software engineer with over 17 years of experience building modern web applications, game engines, WebGL/Canvas graphics, and AI-driven workflows.</p>
<ul>
<li>Grab the source code, Vitest suite, and benchmark harness on <a href="https://github.com/m2-md/broad-phase-collision-spatial-hash">GitHub</a>, or try the <a href="https://m2-md.github.io/broad-phase-collision-spatial-hash/">interactive live demo</a> directly in your browser.</li>
<li>Follow along on <a href="https://linkedin.com/in/mustafamorbel">LinkedIn</a> and <a href="https://x.com/mustafamorbel">X / Twitter (@mustafamorbel)</a> for upcoming articles on Canvas architecture and TypeScript performance.</li>
<li>Grab the complete Canvas 2D &amp; Game Physics Starter Kit on <a href="https://www.buymeacoffee.com/mkare/e/599265">Buy Me a Coffee</a>.</li>
<li>If you found this useful, leave a clap and share how you’ve tuned broad-phase in your own projects! 🧠💬</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[No Need to Wipe the Whole Table: Dirty Rectangle Rendering in Canvas 2D]]></title><description><![CDATA[Originally published on Medium. Read on Medium for free via Friend Link. 🎮 Try the Live Interactive Demo · 📦 GitHub Repo & Vitest Suite · ⚡ Get the TS 2D…]]></description><link>https://mkare.hashnode.dev/no-need-to-wipe-the-whole-table-dirty-rectangle-rendering-in-canvas-2d</link><guid isPermaLink="true">https://mkare.hashnode.dev/no-need-to-wipe-the-whole-table-dirty-rectangle-rendering-in-canvas-2d</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[canvas]]></category><category><![CDATA[performance]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Fri, 20 Nov 2026 19:13:38 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium. <a href="https://medium.com/@mkare/no-need-to-wipe-the-whole-table-dirty-rectangle-rendering-in-canvas-2d-50de001bf7b1?sk=8798d90f87a4c6b379f6d18dc68fe93b">Read on Medium for free via Friend Link</a>.</em></p>
<p>🎮 <strong><a href="https://m2-md.github.io/dirty-rectangle-rendering/">Try the Live Interactive Demo</a></strong> · 📦 <strong><a href="https://github.com/m2-md/dirty-rectangle-rendering">GitHub Repo &amp; Vitest Suite</a></strong> · ⚡ <strong><a href="https://www.buymeacoffee.com/mkare/e/599265">Get the TS 2D Canvas Physics Starter Kit</a></strong></p>
</blockquote>
<p><img src="https://raw.githubusercontent.com/m2-md/dirty-rectangle-rendering/main/assets/demo.gif" alt="Dirty Rectangle Rendering Canvas 2D Demo" /></p>
<blockquote>
<p><a href="https://m2-md.github.io/dirty-rectangle-rendering/">Try the Interactive Live Demo</a> · <a href="https://github.com/m2-md/dirty-rectangle-rendering">Full TypeScript Source &amp; Tests on GitHub</a></p>
</blockquote>
<h3>Quick takeaways</h3>
<ul>
<li>With 5 moving objects out of 2,000, dirty-rectangle rendering cuts draws by up to 97%, processing 52.7 sprites per frame instead of 2,000.</li>
<li>A ratio-based merge rule snowballs and inflates dirty area by a third; a fixed <code>maxWaste</code> pixel budget (<code>2,000 px²</code>) cuts clip regions by 40% while keeping dirty area at 12.5%.</li>
<li>Above 5% moving objects, <code>DirtyTracker</code> automatically falls back to a full redraw (<code>0.015 ms</code> overhead) instead of burning <code>44 ms</code> merging rectangles.</li>
<li>A scrolling camera invalidates the entire screen every frame, so when the camera moves, skip dirty-rects and use layered canvases or frustum culling instead.</li>
</ul>
<p>Every canvas demo I have built in this series starts its draw function with the exact same reflex: wiping the entire canvas clean.</p>
<pre><code class="language-ts">// BEFORE — the opening line of most demos in this series.
// Still present in full-redraw mode (src/main.ts), absent on the dirty-rect path.
ctx.clearRect(0, 0, canvas.width, canvas.height);
</code></pre>
<p>It was there in the <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">2D physics engine</a> and the Part 4 object pool demo (painting over with <code>fillRect</code>), and it stayed unchanged in the <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8">HiDPI Retina canvas</a> and the <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11">fixed timestep loop</a>. It becomes muscle memory: start the frame, wipe everything, redraw everything. Nobody questions it because it works.</p>
<p>I finally stopped in front of that line while building an inventory screen. There were over 300 item slots on screen, and every single one of them was sitting completely still except the one I was dragging with my mouse. For that single dragged slot, I was redrawing all 300 items every frame.</p>
<p>Imagine spilling a single drop of coffee in the kitchen and then wiping the entire table, the chairs, the countertops, and the cabinet doors from scratch, 60 times a second.</p>
<p>We can break that reflex and wipe only the spots that actually got dirty.</p>
<h3>Wiping everything every frame</h3>
<p>Putting a number on the bill makes the wasted work concrete.</p>
<p>A typical Canvas 2D frame pays two costs. The first is pixel cost: <code>clearRect</code> and every <code>fillRect</code> or <code>drawImage</code> writes pixels to be composited on the GPU. Even a modest 640×360 canvas is 230,400 pixels per frame, and on a Retina display with <code>devicePixelRatio = 2</code>, that jumps fourfold.</p>
<p>The second is call cost: the <code>save</code>, <code>translate</code>, <code>beginPath</code>, <code>fill</code>, and <code>restore</code> calls issued for every object. Canvas 2D pays a fixed overhead per draw call, and it scales linearly with object count.</p>
<p>In a scene with 2,000 objects where only 5 are moving, redrawing the other 1,995 buys us nothing. We write the exact same pixels to the exact same coordinates. The canvas content was already right; we erased it just so we could make it right again.</p>
<p>Canvas 2D gives us a guarantee we rarely cash in on: unless you call <code>clearRect</code>, the canvas is persistent. Anything you draw stays put until you erase it. Throughout this entire series, we threw that guarantee away and opened a blank page every frame. Dirty rectangle rendering is how you turn that persistence into performance.</p>
<h3>The dirty region idea</h3>
<p>The idea fits in one sentence: mark every region whose pixels may have changed during the frame, clear only those regions, and redraw only the objects that touch them.</p>
<p>Back to the kitchen table. If coffee spills in a four-inch spot on the top-left corner, you wipe that four-inch spot plus a finger's width of margin around it, and leave the rest of the table alone.</p>
<p>First, we need a rectangle type and pure geometry helpers. This entire file is 100% testable and never touches the DOM:</p>
<pre><code class="language-ts">// src/rect.ts
export interface Rect {
  x: number;
  y: number;
  w: number;
  h: number;
}

// Touching edges do not count as intersecting: half-open interval [x, x+w).
export function rectIntersects(a: Rect, b: Rect): boolean {
  return (
    a.x &lt; b.x + b.w &amp;&amp; b.x &lt; a.x + a.w &amp;&amp; a.y &lt; b.y + b.h &amp;&amp; b.y &lt; a.y + a.h
  );
}

// Smallest rectangle containing both inputs.
export function rectUnion(a: Rect, b: Rect): Rect {
  const x = Math.min(a.x, b.x);
  const y = Math.min(a.y, b.y);
  const right = Math.max(a.x + a.w, b.x + b.w);
  const bottom = Math.max(a.y + a.h, b.y + b.h);
  return { x, y, w: right - x, h: bottom - y };
}

export function rectArea(r: Rect): number {
  return Math.max(0, r.w) * Math.max(0, r.h);
}

export function rectIntersectionArea(a: Rect, b: Rect): number {
  const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
  const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
  return w &gt; 0 &amp;&amp; h &gt; 0 ? w * h : 0;
}
</code></pre>
<p>That margin matters because Canvas 2D applies anti-aliasing: the edge pixels of a circle or diagonal line are painted semi-transparently, and that shading can bleed one pixel outside the object's geometric bounds. If you clear only the exact bounding box, those half-pixels stay behind, and every moving object leaves a faint ghost trail in its wake. I hit this exact bug on my first run: a pale gray tail followed every moving square, and I could not figure out where it came from until I turned on dirty-region outlines.</p>
<p>The fix is a single step. Inflate every dirty rectangle by one pixel, then snap it outward to integer coordinates:</p>
<pre><code class="language-ts">// src/rect.ts (continued)
export function expandRect(r: Rect, pad = 1): Rect {
  return { x: r.x - pad, y: r.y - pad, w: r.w + pad * 2, h: r.h + pad * 2 };
}

// Snap fractional coordinates outward to integers:
// not even a half-pixel escapes outside.
export function snapRect(r: Rect): Rect {
  const x = Math.floor(r.x);
  const y = Math.floor(r.y);
  return { x, y, w: Math.ceil(r.x + r.w) - x, h: Math.ceil(r.y + r.h) - y };
}

// Clip anything extending outside the canvas bounds.
export function clipRect(r: Rect, bounds: Rect): Rect {
  const x = Math.max(r.x, bounds.x);
  const y = Math.max(r.y, bounds.y);
  const right = Math.min(r.x + r.w, bounds.x + bounds.w);
  const bottom = Math.min(r.y + r.h, bounds.y + bounds.h);
  return { x, y, w: Math.max(0, right - x), h: Math.max(0, bottom - y) };
}
</code></pre>
<p>If you use <code>shadowBlur</code> or a thick <code>lineWidth</code>, 1 pixel will not be enough; set <code>pad</code> to the radius of your effect. The rule is simple: <code>pad</code> must be at least the farthest distance a stroke or shadow can bleed past the geometric bounding box.</p>
<h3>Collecting dirty rectangles</h3>
<p>When a box moves from point A to point B, instinct says B is the dirty region because that is where the box sits now. An image of the box is still sitting at A, though, and nobody erased it. Because the canvas is persistent, clearing only B and drawing the box there leaves two boxes on screen: one real, one ghost.</p>
<p>A moving object dirties two places at once: where it left and where it arrived. If a leaky mug slides from one end of the table to the other, you wipe both the old ring and the new ring.</p>
<p>That is why <code>DirtyTracker</code> starts with <code>markMoved</code>:</p>
<pre><code class="language-ts">// src/dirty.ts
import { type Rect, clipRect, expandRect, rectArea, snapRect } from "./rect";
import { mergeRects } from "./merge";

export interface DirtyOptions {
  pad?: number; // anti-aliasing margin (px)
  maxWaste?: number; // acceptable empty area when merging (px²)
  maxRegions?: number;
}

export class DirtyTracker {
  private rects: Rect[] = [];
  private fullyDirty = false;
  private readonly pad: number;
  private readonly maxWaste: number;
  private readonly maxRegions: number;

  constructor(
    private readonly bounds: Rect,
    options: DirtyOptions = {},
  ) {
    this.pad = options.pad ?? 1;
    this.maxWaste = options.maxWaste ?? 2000;
    this.maxRegions = options.maxRegions ?? 24;
  }

  markRect(r: Rect): void {
    if (this.fullyDirty) return; // everything is already dirty, no need to track
    const clipped = clipRect(snapRect(expandRect(r, this.pad)), this.bounds);
    if (rectArea(clipped) &gt; 0) this.rects.push(clipped);
  }

  // A moving object dirties TWO places: where it left and where it went.
  markMoved(prev: Rect, next: Rect): void {
    this.markRect(prev);
    this.markRect(next);
  }

  markAll(): void {
    this.fullyDirty = true;
    this.rects = [{ ...this.bounds }];
  }

  regions(): Rect[] {
    if (this.fullyDirty) return [{ ...this.bounds }];
    // Merging scans pairs O(n²): when input grows large, its own cost
    // exceeds drawing. Bail out if we exceed 4x the region cap.
    if (this.rects.length &gt; this.maxRegions * 4) return [{ ...this.bounds }];
    const merged = mergeRects(this.rects, this.maxWaste);
    // Too fragmented? A single full redraw is cheaper.
    if (merged.length &gt; this.maxRegions) return [{ ...this.bounds }];
    return merged;
  }

  clear(): void {
    this.rects.length = 0;
    this.fullyDirty = false;
  }

  get pendingCount(): number {
    return this.rects.length;
  }

  // Raw unmerged dirty rectangles: useful for metrics and debugging.
  pending(): Rect[] {
    return this.rects.map((r) =&gt; ({ ...r }));
  }
}
</code></pre>
<p>Position is not the only thing that changes. Appearance changes too (color, selection state, animation frame, opacity). A button that never moves but changes color on hover is still dirty. Giving each object a small <code>dirty</code> flag and calling <code>markRect(obj.bounds)</code> when it is raised keeps everything clean: <code>markMoved</code> handles motion, and <code>markRect</code> handles appearance.</p>
<p><code>markAll()</code> is your escape hatch. Window resized, theme switched, scene reloaded: everything is dirty, no argument needed.</p>
<p>That first guard inside <code>regions()</code> came directly from profiling. The merger scans pairs (<code>O(n²)</code>), so when the input list swells, its own cost explodes. In my 2,000-object scene with 200 movers, just merging rectangles burned 44 ms per frame, blowing the entire frame budget before a single pixel was drawn. Bailing out to a full redraw whenever raw rectangles exceed four times <code>maxRegions</code> dropped that exact scenario to 0.029 ms. (You will not see that 44 ms in <code>npm run bench</code>; I measured it manually with <code>simulate(2000, 200, { maxRegions: 1000 })</code>, while 0.029 ms is the default config shown in the final decision table.) Always measure the cost of an optimization itself.</p>
<h3>To merge or to draw separately</h3>
<p>We have a list of dirty rectangles. Looping over them directly runs into two problems. First, if two regions overlap, you clear and redraw the overlapping area twice. Second, every region pays a fixed <code>save</code>/<code>clip</code>/<code>restore</code> tax; a hundred tiny regions can cost more than one medium-sized region.</p>
<p>You do not dip the mop twice for two coffee drops sitting an inch apart; you wipe them in one pass. If one drop is in the kitchen and the other is in the living room, though, forcing a single sweep means mopping the entire hallway in between.</p>
<p>The metric is simple: how much empty waste area does merging two rectangles introduce? Whatever the bounding union covers beyond the actual area of the two rectangles is wasted pixels we will clear for nothing.</p>
<pre><code class="language-ts">// src/merge.ts
import {
  type Rect,
  rectArea,
  rectIntersectionArea,
  rectIntersects,
  rectUnion,
} from "./rect";

// How many extra pixels would we clear for nothing if we merge a and b?
export function mergeWaste(a: Rect, b: Rect): number {
  const covered = rectArea(a) + rectArea(b) - rectIntersectionArea(a, b);
  return rectArea(rectUnion(a, b)) - covered;
}

export function mergeRects(rects: Rect[], maxWaste = 0): Rect[] {
  const out: Rect[] = rects.map((r) =&gt; ({ ...r }));

  let changed = true;
  while (changed) {
    changed = false;
    let bi = -1;
    let bj = -1;
    let best = Infinity;

    for (let i = 0; i &lt; out.length; i++) {
      for (let j = i + 1; j &lt; out.length; j++) {
        // Overlapping rects always merge: no point clearing twice.
        if (rectIntersects(out[i], out[j])) {
          bi = i;
          bj = j;
          best = -1;
          break;
        }
        const waste = mergeWaste(out[i], out[j]);
        if (waste &lt;= maxWaste &amp;&amp; waste &lt; best) {
          best = waste;
          bi = i;
          bj = j;
        }
      }
      if (best === -1) break;
    }

    if (bi &gt;= 0) {
      out[bi] = rectUnion(out[bi], out[bj]);
      out.splice(bj, 1);
      changed = true;
    }
  }
  return out;
}
</code></pre>
<p>On every pass, we pick the pair with the least waste and merge them, repeating until no eligible pairs remain. Overlapping rectangles bypass the threshold completely because leaving them separate buys us nothing.</p>
<p>In my first version of this function, I made a mistake I am slightly embarrassed to admit: I wrote the threshold as a ratio ("merge if the union's area is at most 1.5× the sum of the two rectangles' areas"). It sounded reasonable at the time. I kept that version in the repo so we can compare them side by side:</p>
<pre><code class="language-ts">// src/merge.ts (initial version kept for benchmark comparison)
export function mergeRectsRatio(rects: Rect[], maxGrowth = 1.5): Rect[] {
  const out: Rect[] = rects.map((r) =&gt; ({ ...r }));

  let changed = true;
  while (changed) {
    changed = false;
    outer: for (let i = 0; i &lt; out.length; i++) {
      for (let j = i + 1; j &lt; out.length; j++) {
        const union = rectUnion(out[i], out[j]);
        // Snowball effect: as the merged rect grows, this threshold grows too.
        if (
          rectArea(union) &lt;=
          maxGrowth * (rectArea(out[i]) + rectArea(out[j]))
        ) {
          out[i] = union;
          out.splice(j, 1);
          changed = true;
          break outer;
        }
      }
    }
  }
  return out;
}
</code></pre>
<p>The bug is the snowball effect. A ratio threshold gets more generous as the merged rectangle grows: larger area means a larger 1.5× budget, which makes swallowing the next neighbor even easier. I measured it over 300 frames in my 2,000-object scene with 40 movers:</p>
<pre><code class="language-text">Merge Rule                      Regions/f   Dirty Area   Sprites/f
------------------------------------------------------------------
No merge (overlaps only)             34.8         6.3%       415.8
Ratio threshold 1.5                  32.1         8.4%       446.5
</code></pre>
<p>At first glance the numbers look mild, but the verdict is clear: region count barely budged (34.8 down to 32.1), while dirty area jumped by a third and we drew 30 extra sprites every frame. I paid more and got nothing in return. With larger sprites, that snowball rolls even faster because the growth is baked into the math of ratio thresholds.</p>
<p>Switching to an absolute waste budget (in square pixels) made the behavior predictable because the threshold never inflates as regions grow:</p>
<pre><code class="language-text">maxWaste (px²)    Regions/frame    Dirty Area    Sprites/frame
--------------------------------------------------------------
0                          34.8          6.3%            415.8
500                        31.9          6.7%            414.7
2,000                      20.9         12.5%            521.1
8,000                      10.4         31.1%            885.5
32,000                      1.4         89.8%          1,899.5
∞ (single box)              1.0         94.1%          1,965.1
</code></pre>
<p><em>(640×360 canvas, 2,000 sprites, 40 movers, seeded scene, 300-frame average. Reproduced verbatim with <code>npm run bench</code>; counts are deterministic and independent of machine speed.)</em></p>
<p>Here is how to read that table: <code>maxWaste = 500</code> is practically free, trimming three regions while adding less than half a point of dirty area. At <code>2,000</code>, the real tradeoff appears: region count drops by 40% while dirty area doubles, yet 12.5% is still only one-eighth of the canvas, or 28,800 pixels. Past <code>8,000</code>, dirty area explodes and you hand every microsecond saved on <code>clip</code> calls right back to pixel fill. At infinity, you have abandoned the technique altogether.</p>
<p>That is why <code>DirtyTracker</code> defaults to <code>2,000</code>: it cuts the <code>save</code>/<code>clip</code>/<code>restore</code> overhead by 40% while keeping the dirty area small. If your sprites are larger or more scattered than mine, a different row will win. Re-run the table on your own scene.</p>
<h3>Constraining draws with <code>clip()</code></h3>
<p>Once the regions are ready, drawing them has its own catch.</p>
<p>Clearing a region with <code>clearRect</code> and drawing the touching sprites is not enough, because a sprite that partially overlaps a dirty region will still try to draw its entire body. Repainting the part outside the dirty region might look harmless until alpha blending enters the picture: painting a semi-transparent edge twice darkens it, leaving ugly artifacts along the seam.</p>
<p>You do not let the mop wander outside the square you just cleared. That is exactly what <code>ctx.clip()</code> does: after calling it, no draw call can write a single pixel outside the path you defined.</p>
<p>Our sprite interface stays minimal, requiring only an AABB (axis-aligned bounding box):</p>
<pre><code class="language-ts">// src/scene.ts
import type { HasBounds } from "./query";

export interface Sprite extends HasBounds {
  id: number;
  vx: number;
  vy: number;
  color: string;
}
</code></pre>
<pre><code class="language-ts">// src/render.ts
import type { Rect } from "./rect";
import type { Sprite } from "./scene";
import type { GridIndex } from "./query";

export function drawRegion(
  ctx: CanvasRenderingContext2D,
  region: Rect,
  index: GridIndex&lt;Sprite&gt;,
  drawSprite: (ctx: CanvasRenderingContext2D, s: Sprite) =&gt; void,
): number {
  ctx.save();
  ctx.beginPath();
  ctx.rect(region.x, region.y, region.w, region.h);
  ctx.clip(); // nothing leaks outside
  ctx.clearRect(region.x, region.y, region.w, region.h); // clear only this box

  const touching = index.query(region);
  for (const sprite of touching) drawSprite(ctx, sprite);

  ctx.restore(); // release the clip so the next region sets its own
  return touching.length; // metric: how many sprites we drew in this region
}
</code></pre>
<p><code>ctx.restore()</code> is mandatory. A clip region cannot be undone; it can only be scoped out with a <code>save</code>/<code>restore</code> pair. Forget it once, and the second region clips against the intersection with the first, silently erasing half your screen.</p>
<p><code>index.query(region)</code> connects directly to the next article in this series (Up Next: <em>Broad-Phase Collision &amp; Spatial Hashing</em>), where we divide the world into uniform grid cells to ask which bodies are near each other. Here we use the same spatial query to ask which sprites touch a given rectangle.</p>
<pre><code class="language-ts">// src/query.ts
import { type Rect, rectIntersects } from "./rect";

export interface HasBounds {
  bounds: Rect;
}

// Ground truth reference: check every item. Used as the oracle in tests.
export function queryBrute&lt;T extends HasBounds&gt;(items: T[], region: Rect): T[] {
  return items.filter((it) =&gt; rectIntersects(it.bounds, region));
}

export class GridIndex&lt;T extends HasBounds&gt; {
  private cells = new Map&lt;string, number[]&gt;();
  private items: T[] = [];

  constructor(public readonly cellSize: number) {}

  clear(): void {
    this.cells.clear();
    this.items.length = 0;
  }

  private cellOf(v: number): number {
    return Math.floor(v / this.cellSize);
  }

  insert(item: T): void {
    const id = this.items.length;
    this.items.push(item);
    const b = item.bounds;
    // Register the item in EVERY cell its AABB touches.
    for (let cx = this.cellOf(b.x); cx &lt;= this.cellOf(b.x + b.w); cx++) {
      for (let cy = this.cellOf(b.y); cy &lt;= this.cellOf(b.y + b.h); cy++) {
        const key = cx + "," + cy;
        let cell = this.cells.get(key);
        if (!cell) {
          cell = [];
          this.cells.set(key, cell);
        }
        cell.push(id);
      }
    }
  }

  query(region: Rect): T[] {
    const seen = new Set&lt;number&gt;();
    const out: T[] = [];
    for (
      let cx = this.cellOf(region.x);
      cx &lt;= this.cellOf(region.x + region.w);
      cx++
    ) {
      for (
        let cy = this.cellOf(region.y);
        cy &lt;= this.cellOf(region.y + region.h);
        cy++
      ) {
        const cell = this.cells.get(cx + "," + cy);
        if (!cell) continue;
        for (const id of cell) {
          if (seen.has(id)) continue; // same item can span multiple cells
          seen.add(id);
          const item = this.items[id];
          if (rectIntersects(item.bounds, region)) out.push(item);
        }
      }
    }
    return out;
  }
}
</code></pre>
<p>One warning: draw order. <code>query</code> returns items in cell traversal order, not insertion order. If your sprites overlap and z-order matters, sort the returned array by draw order before rendering. Otherwise, layer order breaks exclusively inside dirty regions, putting a background box on top of a foreground box. That is a miserable bug to track down because it only appears where sprites overlap and only when that spot gets dirty.</p>
<p>Now let's wire up a complete frame from start to finish:</p>
<pre><code class="language-ts">// src/loop.ts
import type { Rect } from "./rect";
import { DirtyTracker } from "./dirty";
import { GridIndex } from "./query";
import { drawRegion } from "./render";
import type { Sprite } from "./scene";

const CANVAS: Rect = { x: 0, y: 0, w: 640, h: 360 };

export function makeFrame(
  ctx: CanvasRenderingContext2D,
  sprites: Sprite[],
  drawSprite: (ctx: CanvasRenderingContext2D, s: Sprite) =&gt; void,
) {
  const tracker = new DirtyTracker(CANVAS, { pad: 1, maxWaste: 2000 });
  const index = new GridIndex&lt;Sprite&gt;(64);

  return function frame(dt: number) {
    tracker.clear();

    // 1. Update positions and mark dirty regions
    for (const sprite of sprites) {
      if (sprite.vx === 0 &amp;&amp; sprite.vy === 0) continue;
      const prev = { ...sprite.bounds };
      sprite.bounds = {
        ...sprite.bounds,
        x: sprite.bounds.x + sprite.vx * dt,
        y: sprite.bounds.y + sprite.vy * dt,
      };
      tracker.markMoved(prev, sprite.bounds);
    }

    // 2. Rebuild spatial index (ALL sprites, not just movers:
    //    static sprites can overlap a dirty region too)
    index.clear();
    for (const sprite of sprites) index.insert(sprite);

    // 3. Draw only dirty regions
    let drawn = 0;
    let dirtyPixels = 0;
    for (const region of tracker.regions()) {
      drawn += drawRegion(ctx, region, index, drawSprite);
      dirtyPixels += region.w * region.h;
    }

    return { drawn, dirtyPixels, total: sprites.length };
  };
}
</code></pre>
<p>Do not skip the comment on step two. We insert all sprites into the index, not just the moving ones. A dirty region cleared behind a moving sprite also erases any static sprite underneath it, so that static sprite must be redrawn. When you lift a mug off the table, the coaster underneath shows back up, so you have to paint it too.</p>
<h3>The moment a camera breaks everything</h3>
<p>One common scenario breaks this technique outright: a scrolling camera (later in this series, we will build a side-scroller with per-layer parallax multipliers using this same pattern):</p>
<pre><code class="language-ts">// Typical scrolling camera setup — illustrative only, NOT in this repo
// (src/ never calls translate).
ctx.save();
ctx.translate(-camera.x, -camera.y);
drawWorld(ctx);
ctx.restore();
</code></pre>
<p>When the player walks right and <code>camera.x</code> increases by a few pixels, every pixel on screen changes. Shifting the camera by even one pixel moves every object on the canvas by one pixel in screen space: ground tiles, clouds, distant hills, all of them. Your dirty region list covers the entire viewport. <code>DirtyTracker</code> works properly and gives the honest answer that everything is dirty.</p>
<p>You wiped the table, then picked up the table and carried it six feet to the left. Now everything is dirty again, and this time it is your fault.</p>
<p>While a camera is scrolling, dirty-rect saves you nothing, and you still pay the tracking tax (<code>markMoved</code> calls, the <code>mergeRects</code> loop, and spatial queries) for zero return. That is why you should watch the camera explicitly and trigger the escape hatch:</p>
<pre><code class="language-ts">// src/camera.ts
import type { DirtyTracker } from "./dirty";

export interface Camera {
  x: number;
  y: number;
}

export class CameraWatcher {
  private lastX: number;
  private lastY: number;

  constructor(camera: Camera) {
    this.lastX = camera.x;
    this.lastY = camera.y;
  }

  // If the camera moved, dirty-rect has nothing to offer: mark everything.
  sync(camera: Camera, tracker: DirtyTracker): boolean {
    const moved = camera.x !== this.lastX || camera.y !== this.lastY;
    this.lastX = camera.x;
    this.lastY = camera.y;
    if (moved) tracker.markAll();
    return moved;
  }
}
</code></pre>
<p>For pure horizontal scrolling, there is a classic rescue trick: blit the canvas onto itself shifted by <code>dx</code>, then draw only the newly exposed strip.</p>
<pre><code class="language-ts">// src/scroll.ts
// Shift the canvas by dx and dirty only the newly exposed strip.
// Fractional dx accumulates anti-aliasing blur; integer steps are mandatory.
export function scrollCanvas(
  ctx: CanvasRenderingContext2D,
  width: number,
  height: number,
  dx: number,
): { x: number; y: number; w: number; h: number } | null {
  if (dx === 0 || Math.abs(dx) &gt;= width) return null;
  const shift = Math.trunc(dx);
  if (shift === 0) return null;

  ctx.save();
  ctx.globalCompositeOperation = "copy"; // no blending, raw pixel copy
  ctx.drawImage(ctx.canvas, -shift, 0);
  ctx.restore();

  return shift &gt; 0
    ? { x: width - shift, y: 0, w: shift, h: height } // new strip on the right
    : { x: 0, y: 0, w: -shift, h: height }; // new strip on the left
}
</code></pre>
<p>This looks clever on paper and feels brittle in production. Camera velocity has to be an integer, or sub-pixel shifts smear the scene into a blur over time. Vertical scrolling forces you to manage two axes. Parallax layers move at different speeds, so a single <code>dx</code> does not work. The moment you add camera zoom, the trick collapses completely. I wired this into a platformer once and ripped it out two days later; the performance gain was not worth the fragility.</p>
<p>My rule of thumb: if the camera moves continuously, do not build dirty-rect at all. Call <code>clearRect(0, 0, W, H)</code> and spend your engineering budget on frustum culling instead. Skipping 1,900 off-screen objects beats cleverly redrawing 100 on-screen ones every time.</p>
<h3>Layered canvases: the cheap alternative</h3>
<p>If you do not want the complexity of tracking, merging, and clipping dirty rectangles, there is a cruder, simpler trick that works for most scenes: split the canvas into layers.</p>
<p>Instead of wiping the tablecloth every meal, you put a disposable placemat on top and only swap the placemat.</p>
<p>You stack two <code>&lt;canvas&gt;</code> elements with CSS. The bottom one holds the static background and is drawn once. The top one is transparent, holds only the moving objects, and gets wiped cleanly every frame. The browser composites the two on the GPU practically for free.</p>
<pre><code class="language-html">&lt;!-- index.html --&gt;
&lt;div class="stage"&gt;
  &lt;canvas id="bg" width="640" height="360"&gt;&lt;/canvas&gt;
  &lt;canvas id="fg" width="640" height="360"&gt;&lt;/canvas&gt;
&lt;/div&gt;
</code></pre>
<pre><code class="language-css">/* index.html &lt;style&gt; block */
.stage { position: relative; width: 640px; height: 360px; background: #0b1220; border: 1px solid #334155; }
.stage canvas { position: absolute; inset: 0; }
</code></pre>
<pre><code class="language-ts">// src/layers.ts
import type { Sprite } from "./scene";

export interface Layers {
  bg: CanvasRenderingContext2D;
  fg: CanvasRenderingContext2D;
  width: number;
  height: number;
}

export function createLayers(
  bgCanvas: HTMLCanvasElement,
  fgCanvas: HTMLCanvasElement,
): Layers {
  const bg = bgCanvas.getContext("2d");
  const fg = fgCanvas.getContext("2d");
  if (!bg || !fg) throw new Error("Failed to get 2d context");
  return { bg, fg, width: bgCanvas.width, height: bgCanvas.height };
}

// Static layer: drawn ONCE on scene setup and resize.
export function paintStatic(
  layers: Layers,
  statics: Sprite[],
  drawSprite: (ctx: CanvasRenderingContext2D, s: Sprite) =&gt; void,
): void {
  layers.bg.clearRect(0, 0, layers.width, layers.height);
  for (const sprite of statics) drawSprite(layers.bg, sprite);
}

// Dynamic layer: cleared in full every frame, but only holds
// a handful of movers — not 2,000.
export function paintDynamic(
  layers: Layers,
  movers: Sprite[],
  drawSprite: (ctx: CanvasRenderingContext2D, s: Sprite) =&gt; void,
): void {
  layers.fg.clearRect(0, 0, layers.width, layers.height);
  for (const sprite of movers) drawSprite(layers.fg, sprite);
}
</code></pre>
<p>Layered canvases do not eliminate pixel cost: you still call <code>clearRect</code> across all 640×360 pixels of the top layer every frame. What they eliminate is call cost, issuing 40 draw calls instead of 2,000.</p>
<p>Dirty-rect saves on both, at the price of <code>markMoved</code> discipline, merge tuning, and z-order sorting.</p>
<p>My selection rule:</p>
<ul>
<li>If you have a clear split between a static background and a few movers, use layered canvases. Twenty lines of code, zero bug risk.</li>
<li>If movers are interleaved with static scenery, z-order is mixed, or a HUD updates a few numbers, use dirty-rect.</li>
<li>If both apply, put the static background on the bottom canvas and run dirty-rect on the top canvas.</li>
</ul>
<h3>Tests: is your dirty region lying?</h3>
<p>This technique has one fatal sin: failing to mark a dirty pixel as dirty. When that happens, ghosts linger on screen, users report corrupted rendering, and you burn two hours debugging sprite code that is completely innocent.</p>
<p>The good news is that every piece of logic here is pure math. <code>Rect</code> operations, merging, tracking, and spatial queries do not need a <code>&lt;canvas&gt;</code> element, and all of them run in headless Vitest:</p>
<pre><code class="language-ts">// test/dirty.test.ts
import { describe, it, expect } from "vitest";
import {
  type Rect,
  expandRect,
  rectArea,
  rectIntersectionArea,
  rectIntersects,
  rectUnion,
} from "../src/rect";
import { mergeRects } from "../src/merge";
import { DirtyTracker } from "../src/dirty";
import { GridIndex, queryBrute, type HasBounds } from "../src/query";

describe("rect math", () =&gt; {
  it("touching edges do not count as intersecting", () =&gt; {
    const a: Rect = { x: 0, y: 0, w: 10, h: 10 };
    expect(rectIntersects(a, { x: 10, y: 0, w: 10, h: 10 })).toBe(false);
    expect(rectIntersects(a, { x: 9, y: 0, w: 10, h: 10 })).toBe(true);
  });

  it("union covers both rectangles", () =&gt; {
    const a: Rect = { x: 0, y: 0, w: 10, h: 10 };
    const b: Rect = { x: 20, y: 5, w: 10, h: 10 };
    expect(rectUnion(a, b)).toEqual({ x: 0, y: 0, w: 30, h: 15 });
    expect(rectArea(rectUnion(a, b))).toBeGreaterThanOrEqual(
      rectArea(a) + rectArea(b),
    );
  });

  it("expandRect grows by 1px in all directions for anti-aliasing", () =&gt; {
    expect(expandRect({ x: 10, y: 10, w: 5, h: 5 }, 1)).toEqual({
      x: 9,
      y: 9,
      w: 7,
      h: 7,
    });
  });

  it("rectIntersectionArea returns 0 for disjoint pairs", () =&gt; {
    const a: Rect = { x: 0, y: 0, w: 10, h: 10 };
    expect(rectIntersectionArea(a, { x: 20, y: 0, w: 10, h: 10 })).toBe(0);
    expect(rectIntersectionArea(a, { x: 5, y: 5, w: 10, h: 10 })).toBe(25);
  });
});

describe("mergeRects", () =&gt; {
  it("merges overlapping rects into one", () =&gt; {
    const merged = mergeRects(
      [
        { x: 0, y: 0, w: 20, h: 20 },
        { x: 10, y: 10, w: 20, h: 20 },
      ],
      0,
    );
    expect(merged).toHaveLength(1);
    expect(merged[0]).toEqual({ x: 0, y: 0, w: 30, h: 30 });
  });

  it("keeps distant rectangles separate", () =&gt; {
    const merged = mergeRects(
      [
        { x: 0, y: 0, w: 10, h: 10 },
        { x: 500, y: 500, w: 10, h: 10 },
      ],
      2000,
    );
    expect(merged).toHaveLength(2);
    expect(merged.reduce((s, r) =&gt; s + rectArea(r), 0)).toBe(200);
  });

  it("merged regions fully cover every input", () =&gt; {
    const input: Rect[] = [
      { x: 0, y: 0, w: 12, h: 12 },
      { x: 8, y: 4, w: 12, h: 12 },
      { x: 300, y: 200, w: 30, h: 30 },
    ];
    const merged = mergeRects(input, 0);
    for (const r of input) {
      // Every input must sit COMPLETELY inside one output: no dirty pixel escapes.
      expect(
        merged.some((m) =&gt; rectIntersectionArea(m, r) === rectArea(r)),
      ).toBe(true);
    }
  });

  it("with 0 waste budget only overlaps merge", () =&gt; {
    const near: Rect[] = [
      { x: 0, y: 0, w: 10, h: 10 },
      { x: 12, y: 0, w: 10, h: 10 }, // 2px gap -&gt; 20px² waste
    ];
    expect(mergeRects(near, 0)).toHaveLength(2);
    expect(mergeRects(near, 20)).toHaveLength(1);
  });
});

describe("DirtyTracker", () =&gt; {
  const bounds: Rect = { x: 0, y: 0, w: 640, h: 360 };

  it("markMoved dirties both old and new positions", () =&gt; {
    const t = new DirtyTracker(bounds, { pad: 1, maxWaste: 0 });
    t.markMoved(
      { x: 10, y: 10, w: 20, h: 20 },
      { x: 300, y: 200, w: 20, h: 20 },
    );
    const regions = t.regions();
    expect(regions).toHaveLength(2);
    expect(
      regions.some((r) =&gt; rectIntersects(r, { x: 10, y: 10, w: 20, h: 20 })),
    ).toBe(true);
    expect(
      regions.some((r) =&gt; rectIntersects(r, { x: 300, y: 200, w: 20, h: 20 })),
    ).toBe(true);
  });

  it("small step merges old and new positions into one region", () =&gt; {
    const t = new DirtyTracker(bounds, { pad: 1, maxWaste: 0 });
    t.markMoved(
      { x: 100, y: 100, w: 20, h: 20 },
      { x: 103, y: 100, w: 20, h: 20 },
    );
    expect(t.regions()).toHaveLength(1);
  });

  it("regions stay clipped within canvas bounds", () =&gt; {
    const t = new DirtyTracker(bounds, { maxWaste: 0 });
    t.markRect({ x: -50, y: -50, w: 100, h: 100 });
    const [r] = t.regions();
    expect(r.x).toBe(0);
    expect(r.y).toBe(0);
    expect(r.x + r.w).toBeLessThanOrEqual(640);
  });

  it("falls back to full redraw when region cap is exceeded", () =&gt; {
    const t = new DirtyTracker(bounds, { pad: 0, maxWaste: 0, maxRegions: 3 });
    for (let i = 0; i &lt; 8; i++)
      t.markRect({ x: i * 70, y: i * 40, w: 10, h: 10 });
    expect(t.regions()).toEqual([bounds]);
  });

  it("markAll dirties everything and swallows subsequent markRect calls", () =&gt; {
    const t = new DirtyTracker(bounds, { maxWaste: 0 });
    t.markAll();
    t.markRect({ x: 5, y: 5, w: 5, h: 5 });
    expect(t.regions()).toEqual([bounds]);
    expect(t.pendingCount).toBe(1);
  });

  it("no dirty regions remain after clear", () =&gt; {
    const t = new DirtyTracker(bounds);
    t.markRect({ x: 5, y: 5, w: 5, h: 5 });
    t.clear();
    expect(t.regions()).toHaveLength(0);
  });
});

interface TestSprite extends HasBounds {
  id: number;
}

function scene(n: number, seed: number): TestSprite[] {
  let s = seed;
  const rand = () =&gt; {
    s = (s * 1103515245 + 12345) &amp; 0x7fffffff;
    return s / 0x7fffffff;
  };
  return Array.from({ length: n }, (_, id) =&gt; ({
    id,
    bounds: {
      x: rand() * 620,
      y: rand() * 340,
      w: 4 + rand() * 40,
      h: 4 + rand() * 40,
    },
  }));
}

describe("spatial query for touching sprites", () =&gt; {
  it("grid query matches brute-force set exactly", () =&gt; {
    const items = scene(400, 9);
    const grid = new GridIndex&lt;TestSprite&gt;(64);
    for (const it of items) grid.insert(it);

    const regions: Rect[] = [
      { x: 0, y: 0, w: 50, h: 50 }, // corner
      { x: 200, y: 120, w: 90, h: 40 }, // center
      { x: 610, y: 330, w: 30, h: 30 }, // edge-clipping
      { x: 0, y: 0, w: 640, h: 360 }, // full screen
    ];
    for (const region of regions) {
      const fromGrid = grid
        .query(region)
        .map((s) =&gt; s.id)
        .sort((a, b) =&gt; a - b);
      const brute = queryBrute(items, region)
        .map((s) =&gt; s.id)
        .sort((a, b) =&gt; a - b);
      expect(fromGrid).toEqual(brute);
    }
  });

  it("matches brute-force even with negative coordinates", () =&gt; {
    const items = scene(300, 17);
    const grid = new GridIndex&lt;TestSprite&gt;(48);
    for (const it of items) grid.insert(it);
    const region: Rect = { x: -80, y: -40, w: 200, h: 150 };
    const fromGrid = grid
      .query(region)
      .map((s) =&gt; s.id)
      .sort((a, b) =&gt; a - b);
    const brute = queryBrute(items, region)
      .map((s) =&gt; s.id)
      .sort((a, b) =&gt; a - b);
    expect(fromGrid).toEqual(brute);
  });

  it("never returns the same sprite twice", () =&gt; {
    const items = scene(200, 3);
    const grid = new GridIndex&lt;TestSprite&gt;(32);
    for (const it of items) grid.insert(it);
    const ids = grid.query({ x: 0, y: 0, w: 640, h: 360 }).map((s) =&gt; s.id);
    expect(new Set(ids).size).toBe(ids.length);
  });
});
</code></pre>
<p>Two tests matter above all others. First, "merged regions fully cover every input": after merging, every original dirty rectangle must sit completely inside one output region. If its intersection area equals its own area, nothing escaped. If that test turns red, ghosts are guaranteed.</p>
<p>Second, the brute-force oracle. The set returned by <code>GridIndex</code> must match "check every item one by one" identically. We will use this exact discipline in the upcoming broad-phase collision article: validate your fast spatial structure against the slow, exact one. I tested four regions (corner, center, edge-clipping, full screen) because off-by-one cell math almost always hides at canvas boundaries.</p>
<p>If those two tests are green, everything else is visual tuning.</p>
<h3>When it pays off, and when it does not</h3>
<p>In the same 2,000-sprite scene, I varied the number of moving sprites and averaged 300 frames (<code>maxWaste = 2000</code>, <code>maxRegions = 24</code>):</p>
<pre><code class="language-text">Movers   Ratio   Reg/f   Dirty   Drawn/f   vs Full   Tracking
-------------------------------------------------------------
5        0.25%     4.6    1.0%      52.7        3%   0.006 ms
20          1%    14.6    5.2%     260.2       13%   0.254 ms
40          2%    20.9   12.5%     521.1       26%   1.903 ms
100         5%     1.0  100.0%   2,000.0      100%   0.015 ms
200        10%     1.0  100.0%   2,000.0      100%   0.029 ms
400        20%     1.0  100.0%   2,000.0      100%   0.058 ms
2,000     100%     1.0  100.0%   2,000.0      100%   0.294 ms
</code></pre>
<p>The last column is per-frame tracking cost (marking plus merging, excluding drawing, on an Apple M2 Pro with Node 22).</p>
<p>The curve turned out steeper than I expected. With 5 movers, we do only 3% of the work, better than a 30× reduction. At 20 movers, 13%; at 40 movers, 26%. Then comes the cliff: at 100 movers, the technique shuts itself off and drops back to a full redraw.</p>
<p>That cliff is the bailout guard doing its job. A hundred moving sprites generate 200 raw dirty rectangles per frame. Because that exceeds four times <code>maxRegions</code>, <code>regions()</code> skips merging altogether and reports everything as dirty. I built that behavior intentionally, because nothing is sneakier than an optimization that slows down your frame rate without telling you.</p>
<p>The bottom row is the honest limit: when every object moves, dirty-rect loses. It performs the exact same draw work as a full redraw (2,000 sprites, 100% of the canvas) while charging an extra 0.29 ms per frame for tracking. At 60 fps, that is 1.8% of your entire frame budget burned for zero return.</p>
<p>Here is my decision rule:</p>
<ul>
<li>Under 1% moving objects, dirty-rect wins decisively. Inventories, maps, tables, editors, and HUD-heavy screens live here.</li>
<li>Between 1% and 2%, it still wins, though tracking cost becomes visible (1.9 ms/frame at 2% in my test). Measure it.</li>
<li>Above 5%, don't bother. The bailout already shuts it off. Call <code>clearRect(0, 0, W, H)</code> and optimize drawing itself with sprite batching, offscreen pre-rendering, and object pools.</li>
<li>With a continuously scrolling camera, skip dirty-rect regardless of mover ratio.</li>
<li>In a fixed-camera tile game, it is a textbook fit because terrain tiles never move and only characters and effects dirty the screen.</li>
</ul>
<p>Never guess without measuring. The live demo includes a toggle that outlines dirty regions on screen, and turning it on shows you in a second which object is needlessly dirtying the canvas. Drag the movers slider up to 100 in the demo and watch the outline snap around the entire screen: that is the 100% row of the table right before your eyes.</p>
<h3>Summary</h3>
<ol>
<li>A Canvas 2D surface is persistent. Calling <code>clearRect(0, 0, W, H)</code> throws that guarantee away every frame; dirty-rectangle rendering cashes it in.</li>
<li>A moving object dirties two places at once: where it left and where it arrived. That is why <code>markMoved(prev, next)</code> exists.</li>
<li>Anti-aliasing bleeds past geometric bounds. Inflate every dirty rectangle by at least 1 px and snap outward to integers, or ghost trails will stay behind.</li>
<li>Never write merge thresholds as area ratios; they snowball and inflate dirty area for no gain. Use an absolute pixel-waste budget (<code>px²</code>), where <code>500</code> to <code>2,000</code> was the sweet spot in my scene.</li>
<li>Per region, run <code>save</code>, <code>clip</code>, <code>clearRect</code>, draw, and <code>restore</code>. Skip <code>restore</code> and the next region intersects the previous clip, silently hiding the screen.</li>
<li>Finding every sprite touching a dirty rectangle is a spatial query; the same grid we will use for broad-phase collision in the next article handles it here. Sort by z-order if sprites overlap.</li>
<li>A scrolling camera invalidates the whole technique: shift one pixel and the entire screen is dirty. Accept it, call <code>markAll()</code>, and spend your budget on culling.</li>
<li>The simple alternative is layered canvases: static background on the bottom once, movers on top every frame. Twenty lines, zero bug risk, plenty for most scenes.</li>
<li>Let mover ratio decide: under 1% is a guaranteed win, over 5% is a loss, and at 100% moving, dirty-rect does all the full-redraw work plus tracking overhead. Measure, don't guess.</li>
</ol>
<p>The <a href="https://github.com/m2-md/dirty-rectangle-rendering">GitHub repository</a> runs with three commands: <code>npm test</code> verifies all 17 unit tests across <code>Rect</code> math, merging, tracking, and the spatial index; <code>npm run bench</code> reproduces all three tables locally (count columns are deterministic, only tracking time varies by hardware); and <code>npm run dev</code> launches the interactive demo with dirty-region outlines and a full-redraw toggle (the layered canvas example lives in the same repo). Or launch the <a href="https://m2-md.github.io/dirty-rectangle-rendering/">interactive live demo</a> straight in your browser.</p>
<p>Figuring out why my ratio threshold made things worse took longer than writing the code. On my first benchmark run, I saw the region count drop and celebrated. It took me half an hour to notice the dirty area column, and for that entire half hour I was staring at a table that hid the very thing I had broken. Knowing which column to read matters just as much as writing fast code.</p>
<p>If there is one drop of coffee on the table, clean one drop and leave the rest alone.</p>
<h3>Canvas 2D and game architecture series</h3>
<ul>
<li>Part 1: <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas</a></li>
<li>Part 2: <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8">Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes</a></li>
<li>Part 3: <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11">Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript</a></li>
<li>Part 4: Return the Glass, Not the Trash: Object Pools and Zero-Allocation Game Loops in Canvas <em>(Series entry)</em></li>
<li>Part 5 (This Article): No Need to Wipe the Whole Table: Dirty Rectangle Rendering in Canvas 2D</li>
<li>Part 6 (Up Next): Broad-Phase Collision &amp; Spatial Hashing in Canvas 2D</li>
</ul>
<h3>About the author</h3>
<p>I'm Mustafa Morbel, a software engineer with over 17 years of experience building modern web applications, game engines, WebGL/Canvas graphics, and AI-assisted developer workflows.</p>
<ul>
<li>Explore the full TypeScript source, 17 Vitest tests, and benchmarks in the <a href="https://github.com/m2-md/dirty-rectangle-rendering">GitHub repository</a>, or try the <a href="https://m2-md.github.io/dirty-rectangle-rendering/">interactive live demo</a> in your browser.</li>
<li>Follow me on <a href="https://linkedin.com/in/mustafamorbel">LinkedIn</a> and <a href="https://x.com/mustafamorbel">X / Twitter (@mustafamorbel)</a> for upcoming articles in this series.</li>
</ul>
<p>Have you hit the scrolling-camera wall or tuned dirty-rect budgets in your own Canvas app? I'd love to hear how you solved it.</p>
]]></content:encoded></item><item><title><![CDATA[Return the Cart, Clear the Exit: Object Pools and Zero-Allocation Loops in Canvas]]></title><description><![CDATA[Originally published on Medium. Read on Medium for free via Friend Link. 🎮 Try the Live Pooled vs. Unpooled Demo · 📦 GitHub Repo & 6 Vitest Suites · ⚡…]]></description><link>https://mkare.hashnode.dev/return-the-cart-clear-the-exit-object-pools-and-zero-allocation-loops-in-canvas</link><guid isPermaLink="true">https://mkare.hashnode.dev/return-the-cart-clear-the-exit-object-pools-and-zero-allocation-loops-in-canvas</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[canvas]]></category><category><![CDATA[performance]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Fri, 20 Nov 2026 18:17:29 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium.</em> <a href="https://medium.com/@mkare/return-the-cart-clear-the-exit-object-pools-and-zero-allocation-loops-in-canvas-4051c97ff8a7?source=friends_link&amp;sk=2ed006e6c639a47b92eb324d11a664a6"><em>Read on Medium for free via Friend Link</em></a><em>.</em></p>
<p>🎮 <a href="https://m2-md.github.io/object-pools-zero-allocation/"><strong>Try the Live Pooled vs. Unpooled Demo</strong></a> · 📦 <a href="https://github.com/m2-md/object-pools-zero-allocation"><strong>GitHub Repo &amp; 6 Vitest Suites</strong></a> · ⚡ <a href="https://www.buymeacoffee.com/mkare/e/599265"><strong>Get the TS 2D Canvas Physics Starter Kit</strong></a></p>
</blockquote>
<img src="https://raw.githubusercontent.com/m2-md/object-pools-zero-allocation/main/assets/demo.gif" alt="Interactive Object Pool vs. Unpooled Demo Preview" style="display:block;margin:0 auto" />

<img src="https://miro.medium.com/v2/resize:fit:1400/1*psyveTAFY7qBmLYpcfE6nw.png" alt="Split comparison showing chaotic abandoned shopping carts labeled 36,000 objects and 3,600 arrays on the left versus a tidy cart return bay labeled 347 objects and 0 arrays on the right, both with 279 surviving particles over 60 seconds." style="display:block;margin:0 auto" />

<p><em>Recycling particles with an object pool drops 36,000 object allocations and 3,600 array allocations down to 347 objects and zero arrays over a 60-second scene.</em></p>
<h3>Quick takeaways</h3>
<ul>
<li>Replacing <code>push({...})</code> and <code>filter()</code> with a TypeScript <code>Pool&lt;T&gt;</code> cuts particle allocations from <code>36,000</code> down to <code>347</code> (the exact high-water mark) over 3,600 frames.</li>
<li>An O(1) backward swap-remove removes all <code>3,600</code> per-frame array allocations.</li>
<li>Writing into an <code>out</code> vector (<code>scaleAndAdd</code>) avoids <code>240,000</code> temporary <code>Vec2</code> allocations per second across 1,000 physics bodies.</li>
<li>V8's young-generation scavenger clears sporadic allocations in under a millisecond, so only add a pool when profiling shows a sawtooth heap curve.</li>
</ul>
<p>At a packed supermarket on a Saturday afternoon, if every shopper abandons their cart right outside the exit instead of rolling it back into the return bay, a wall of metal carts piles up at the door within minutes. Incoming shoppers cannot find a cart, and people leaving can barely squeeze through. Soon traffic stops altogether. Staff block off the exit lane, everyone waits while workers haul the pile back to the entrance, and only then does the store move again.</p>
<p>A default particle system in a browser game behaves the same way. In our <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">physics engine article</a>, sparks flew whenever a block cracked. In a falling ball game, every catch triggered a burst. Both used the same familiar pattern: <code>particles.push({...})</code> on every burst, and <code>particles = particles.filter(p =&gt; p.life &gt; 0)</code> on every frame. With a dozen sparks, nobody notices. Once hundreds of particles spawn and expire every second, those abandoned carts pile up at the exit until the Garbage Collector (GC) has to block the lane and clear the jam. When the GC halts the main thread to reclaim memory, a frame drops and your 60 FPS animation hitches.</p>
<p>Instead of abandoning carts at the exit, we can roll them back into a return bay. We will inspect the GC sawtooth pattern in Chrome DevTools, build a generic, type-safe <code>Pool&lt;T&gt;</code>, wire it into a particle system with swap-remove, remove temporary vector allocations from the integration loop, and benchmark both heavy and light workloads to see when pooling helps and when it does not.</p>
<h3>The sawtooth curve</h3>
<p>JavaScript manages memory automatically. When you write <code>{ x: 0, y: 0 }</code>, the engine allocates space on the heap; once nothing references that object, the garbage collector reclaims it without you ever calling <code>free()</code>. In most web apps, that convenience is great. Inside a 60 FPS game loop, though, constant allocation turns into a recurring pause.</p>
<p>Here is the simplified <code>spawn</code> and <code>update</code> logic from our physics demo:</p>
<pre><code class="language-ts">// src/particle.ts — baseline pattern BEFORE optimization (churn)
export interface Particle {
  x: number;
  y: number;
  vx: number;
  vy: number;
  life: number;
  max: number;
}

let particles: Particle[] = [];

export function spawn(x: number, y: number, count: number, rng: () =&gt; number) {
  for (let i = 0; i &lt; count; i++) {
    const a = rng() * Math.PI * 2;
    const speed = 40 + rng() * 150;
    const life = 0.3 + rng() * 0.4;
    particles.push({
      x,
      y,
      vx: Math.cos(a) * speed,
      vy: Math.sin(a) * speed,
      life,
      max: life,
    }); // every call: a brand new object on the heap
  }
}

export function update(dt: number) {
  for (const p of particles) {
    p.life -= dt;
    p.x += p.vx * dt;
    p.y += p.vy * dt;
    p.vy += 220 * dt;
  }
  particles = particles.filter((p) =&gt; p.life &gt; 0); // every frame: a brand new array
}
</code></pre>
<p>This code produces garbage in two places. First, every <code>push({...})</code> allocates a fresh <code>Particle</code> object on the heap. Second, <code>particles.filter(...)</code> allocates a new array on every frame just to drop expired items. If 500 particles are active and one spark dies, <code>filter</code> still allocates a new array and copies the 499 surviving references into it, 60 times a second.</p>
<p>Even though V8's garbage collector is fast, a major collection cycle still has to pause JavaScript on the main thread (a stop-the-world pause). That pause is what drops frames.</p>
<p>You can see this directly in Chrome DevTools. Open the Performance tab, check the Memory box, hit Record, trigger plenty of particle bursts for a few seconds, and stop recording. Look at two tracks:</p>
<ul>
<li>In the JS Heap graph, memory climbs steadily as objects accumulate, then plunges vertically when the garbage collector sweeps the heap. That repeating rise-and-drop shape is a sawtooth curve. Steeper, more frequent teeth mean heavier allocation pressure.</li>
<li>In the Frames track, yellow <code>Major GC</code> or <code>Minor GC</code> blocks line up with each drop in the heap graph, often alongside red markers for dropped frames. Those red markers are the stutters the player feels.</li>
</ul>
<p>The goal is to flatten that sawtooth into a horizontal line by avoiding allocations during gameplay.</p>
<h3>Building a generic object pool</h3>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*btU3HcqrqU8NrG5pN3Fy6Q.png" alt="Comic-style diagram titled The Cart Pool showing shoppers acquiring carts from a free array, releasing them back, and an attendant resetting stale state before reuse." style="display:block;margin:0 auto" />

<p><em>The object pool lifecycle: acquire from free[], release back to the bay, and reset every field so stale state never leaks.</em></p>
<p>Supermarkets solve the cart problem with a return bay at the entrance. You grab an empty cart (<code>acquire</code>), shop with it, and roll it back into the bay when you finish (<code>release</code>). Any leftover receipt or item gets cleared out (<code>reset</code>) so the cart is ready for the next person.</p>
<p>An object pool works the same way. Here is a generic, type-safe <code>Pool&lt;T&gt;</code> in TypeScript:</p>
<pre><code class="language-ts">// src/pool.ts
export interface PoolOptions&lt;T&gt; {
  create: () =&gt; T; // how a new object is produced
  reset: (obj: T) =&gt; void; // how a returned object is cleared
  initial?: number; // how many to keep ready up front
}

export class Pool&lt;T&gt; {
  private free: T[] = []; // the empty carts in the return bay
  private create: () =&gt; T;
  private reset: (obj: T) =&gt; void;

  created = 0; // total carts put into circulation (high-water mark)

  constructor(opts: PoolOptions&lt;T&gt;) {
    this.create = opts.create;
    this.reset = opts.reset;
    for (let i = 0; i &lt; (opts.initial ?? 0); i++) {
      this.free.push(this.make());
    }
  }

  private make(): T {
    this.created++;
    return this.create();
  }

  acquire(): T {
    // If there is a cart in the bay, hand it over; otherwise roll out a new one.
    return this.free.pop() ?? this.make();
  }

  release(obj: T): void {
    this.reset(obj); // empty it first
    this.free.push(obj); // then push it back into the bay
  }

  get available(): number {
    return this.free.length;
  }
}
</code></pre>
<p>Everything depends on one line inside <code>acquire</code>: <code>this.free.pop() ?? this.make()</code>. When an object is waiting in <code>free</code>, we hand it back with zero heap allocation. We only call <code>make()</code> when the bay is empty.</p>
<p>This naturally caps allocations at the high-water mark: the highest number of objects your game needs alive at the same time. If your scene never has more than 347 particles on screen at once, the pool creates 347 objects over its entire lifetime and stops there. During the first few seconds, the pool warms up to that peak. After that, <code>created</code> stays flat and heap allocations drop to zero.</p>
<p><code>reset</code> is a dedicated callback because a returned object still holds whatever values it had when it died. If the next caller gets an unemptied object and does not overwrite every field, you end up with ghost bugs.</p>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*gQ-tSWhMrHHISLZoB8_bfg.png" alt="Comic-style illustration titled The Particle That Flew Backward showing one glowing blue particle shooting backward with stale vy velocity because vy was not reset to 0 on release." style="display:block;margin:0 auto" />

<p><em>Forgetting to reset a single field (vy = 0) leaves stale state on recycled particles and causes subtle ghost bugs.</em></p>
<h3>Wiring the particle system to the pool</h3>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*_WWZE35mo8zCypgRdamTvg.png" alt="Diagram comparing array filter versus swap-remove using shopping carts: filter copies 499 surviving carts into a new array, while swap-remove moves the last cart into the expired slot with 1 move and pops the end." style="display:block;margin:0 auto" />

<p><em>filter() copies 499 surviving references into a brand-new array every frame; backward swap-remove does one swap, pops the tail, and releases the dead particle in O(1).</em></p>
<p>With <code>Pool&lt;T&gt;</code> ready, we can replace <code>push({...})</code> and <code>filter()</code> in the particle emitter. When a particle spawns, we call <code>acquire</code>; when it expires, we call <code>release</code>.</p>
<pre><code class="language-ts">// src/particle-system.ts
import { Pool } from "./pool";
import type { Particle } from "./particle";

export class ParticleSystem {
  private pool: Pool&lt;Particle&gt;;
  private active: Particle[] = []; // the live particles on screen

  constructor(initial = 256) {
    this.pool = new Pool&lt;Particle&gt;({
      initial,
      create: () =&gt; ({ x: 0, y: 0, vx: 0, vy: 0, life: 0, max: 0 }),
      reset: (p) =&gt; {
        p.x = 0;
        p.y = 0;
        p.vx = 0;
        p.vy = 0;
        p.life = 0;
        p.max = 0;
      },
    });
  }

  burst(x: number, y: number, count: number, rng: () =&gt; number) {
    for (let i = 0; i &lt; count; i++) {
      const p = this.pool.acquire(); // not new: taken from the bay
      const a = rng() * Math.PI * 2;
      const speed = 40 + rng() * 150;
      const life = 0.3 + rng() * 0.4;
      p.x = x;
      p.y = y;
      p.vx = Math.cos(a) * speed;
      p.vy = Math.sin(a) * speed;
      p.life = life;
      p.max = life;
      this.active.push(p);
    }
  }

  update(dt: number) {
    // No filter. When one dies, return it to the pool and move the last one into its slot.
    for (let i = this.active.length - 1; i &gt;= 0; i--) {
      const p = this.active[i];
      p.life -= dt;
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.vy += 220 * dt;

      if (p.life &lt;= 0) {
        this.pool.release(p); // return the cart to the bay
        this.active[i] = this.active[this.active.length - 1]; // swap-remove
        this.active.pop();
      }
    }
  }

  get activeCount(): number {
    return this.active.length;
  }

  // Walk the live particles for drawing — without a copy or a new array (zero allocation).
  get particles(): readonly Particle[] {
    return this.active;
  }

  get allocations(): number {
    return this.pool.created;
  }
}
</code></pre>
<p>Inside <code>update</code>, we replace <code>filter</code> with an O(1) swap-remove. When a particle dies, we move the last active particle into its slot and call <code>this.active.pop()</code>.</p>
<p>Iterating backward from <code>length - 1</code> down to <code>0</code> keeps the loop safe: the element swapped into index <code>i</code> came from the end of the array, which we already checked, so no particle gets skipped or updated twice. The per-frame array allocation from <code>filter</code> is gone, and <code>active</code> reuses its backing storage across frames.</p>
<p>In my first prototype of this pool, I forgot to reset <code>vy</code> inside <code>reset</code>. It seemed harmless because <code>burst()</code> assigned fresh velocities anyway. In edge cases where an emitter did not overwrite every coordinate right away, though, recycled particles spawned with their old velocity vectors and shot backward across the screen at supersonic speeds the moment they appeared. It was the same problem as an unemptied shopping cart with someone else's groceries still in the basket.</p>
<p>Always reset every property on release. Leaving stale state on a recycled object leads to bugs that are painful to track down, so we will lock this rule down with a unit test below.</p>
<h3>Zero-allocation vectors in the hot path</h3>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*mr8XxvMw2dAVJ2GieHi__g.png" alt="Factory conveyor illustration titled 240,000 Temporary Vec2s Per Second showing add(a, b) and scale(a, dt) dumping temporary vector objects into a GC bin, contrasted with an in-place out buffer via scaleAndAdd(out, a, b, s)." style="display:block;margin:0 auto" />

<p><em>Pure vector helpers churn 240,000 temporary Vec2 objects per second across 1,000 bodies; writing into an out buffer via scaleAndAdd(out, a, b, s) eliminates the garbage.</em></p>
<p>Recycling particles fixes the emitter, yet temporary vector calculations often create just as much garbage in the same loop.</p>
<p>In <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">our physics engine</a>, helpers like <code>add</code>, <code>sub</code>, and <code>scale</code> were pure, immutable functions that returned a new object literal every time:</p>
<pre><code class="language-ts">// BEFORE — counter-example from basic vector libraries (pure functions)
export const add = (a: Vec2, b: Vec2): Vec2 =&gt; ({ x: a.x + b.x, y: a.y + b.y });
export const scale = (a: Vec2, s: number): Vec2 =&gt; ({ x: a.x * s, y: a.y * s });
</code></pre>
<p>That style reads nicely in normal application code. Inside an integration loop running 60 times a second, it churns through memory fast:</p>
<pre><code class="language-ts">// BEFORE — counter-example: integration with pure functions
b.vel = add(b.vel, scale(gravity, dt)); // 2 new Vec2 objects
b.pos = add(b.pos, scale(b.vel, dt));    // 2 more new Vec2 objects
</code></pre>
<p>That is four temporary <code>Vec2</code> objects per physics body per frame. With 1,000 active bodies, the loop allocates and discards 240,000 tiny objects every second, feeding the same sawtooth curve.</p>
<p>The fix is to switch those hot-path helpers to in-place mutations that write into a caller-supplied <code>out</code> parameter:</p>
<pre><code class="language-ts">// src/vec.ts
export type Vec2 = { x: number; y: number };

export function addInPlace(out: Vec2, a: Vec2, b: Vec2): Vec2 {
  out.x = a.x + b.x;
  out.y = a.y + b.y;
  return out;
}

export function scaleInPlace(out: Vec2, a: Vec2, s: number): Vec2 {
  out.x = a.x * s;
  out.y = a.y * s;
  return out;
}

// out = a + b * s  — exactly the integrator's shape, in a single call
export function scaleAndAdd(out: Vec2, a: Vec2, b: Vec2, s: number): Vec2 {
  out.x = a.x + b.x * s;
  out.y = a.y + b.y * s;
  return out;
}
</code></pre>
<p>Because <code>out</code> can be the same object as <code>a</code>, calling <code>scaleAndAdd(b.vel, b.vel, gravity, dt)</code> updates <code>b.vel</code> in place and drops all four allocations per body to zero:</p>
<pre><code class="language-ts">// AFTER — in-place integration pattern
scaleAndAdd(b.vel, b.vel, gravity, dt); // vel += gravity * dt (0 allocations)
scaleAndAdd(b.pos, b.pos, b.vel, dt);    // pos += vel     * dt (0 allocations)
</code></pre>
<p>When an intermediate step genuinely needs temporary storage, allocate a single static scratch buffer once outside the loop:</p>
<pre><code class="language-ts">// src/vec.ts (continued)
const scratch: Vec2 = { x: 0, y: 0 }; // allocated once, outside the loop

export function reflect(vel: Vec2, normal: Vec2): void {
  const d = 2 * (vel.x * normal.x + vel.y * normal.y);
  scaleInPlace(scratch, normal, d); // scratch = normal * d
  vel.x -= scratch.x;
  vel.y -= scratch.y;
}
</code></pre>
<p>In-place mutations do trade readability for speed. <code>add(a, b)</code> is easy to scan; <code>scaleAndAdd(out, a, b, s)</code> takes more attention to read. Keep in-place vectors for verified hot paths that run thousands of times per frame, and stick to pure functions everywhere else.</p>
<h3>Measuring the wins: empirical benchmarks</h3>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*D5lECeyx-fmR7TWCkzenoA.png" alt="Blueprint tank diagram titled Object Pool Stopped at 347 showing a 347 high-water mark with acquire and release circulation pipes and a gauge stopping at 347 created objects, never creating a 401st object." style="display:block;margin:0 auto" />

<p><em>Once the pool warms up to the scene's 347-particle high-water mark, allocations flatline and never create a 348th object.</em></p>
<p>Saying an approach generates less garbage is only a guess until you measure it. To compare both versions fairly, we use a seeded pseudo-random number generator (<code>mulberry32</code>) so both runs spawn identical particle trajectories in the exact same order:</p>
<pre><code class="language-ts">// src/rng.ts
export function makeRng(seed: number): () =&gt; number {
  let s = seed &gt;&gt;&gt; 0;
  return () =&gt; {
    s = (s + 0x6d2b79f5) | 0;
    let t = Math.imul(s ^ (s &gt;&gt;&gt; 15), 1 | s);
    t = (t + Math.imul(t ^ (t &gt;&gt;&gt; 7), 61 | t)) ^ t;
    return ((t ^ (t &gt;&gt;&gt; 14)) &gt;&gt;&gt; 0) / 4294967296;
  };
}
</code></pre>
<pre><code class="language-ts">// src/bench.ts
export interface BenchResult {
  allocations: number; // number of Particle objects created
  ms: number;          // total execution time
  survived: number;    // number of particles alive at the end
}
</code></pre>
<p>The unpooled baseline counts every object it creates:</p>
<pre><code class="language-ts">// src/bench.ts (baseline)
export function benchBaseline(
  frames: number,
  burstEvery: number,
  burstCount: number,
  seed: number,
): BenchResult {
  const rng = makeRng(seed);
  let particles: Particle[] = [];
  let allocations = 0;
  const dt = 1 / 60;
  const t0 = performance.now();

  for (let f = 0; f &lt; frames; f++) {
    if (f % burstEvery === 0) {
      for (let i = 0; i &lt; burstCount; i++) {
        const a = rng() * Math.PI * 2;
        const speed = 40 + rng() * 150;
        const life = 0.3 + rng() * 0.4;
        particles.push({
          x: 0,
          y: 0,
          vx: Math.cos(a) * speed,
          vy: Math.sin(a) * speed,
          life,
          max: life,
        });
        allocations++;
      }
    }
    for (const p of particles) {
      p.life -= dt;
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.vy += 220 * dt;
    }
    particles = particles.filter((p) =&gt; p.life &gt; 0); // + 1 array allocation per frame
  }

  return {
    allocations,
    ms: performance.now() - t0,
    survived: particles.length,
  };
}
</code></pre>
<p>The pooled version runs the same simulation through <code>ParticleSystem</code> and reads the allocation count from the pool:</p>
<pre><code class="language-ts">// src/bench.ts (pooled)
export function benchPooled(
  frames: number,
  burstEvery: number,
  burstCount: number,
  seed: number,
): BenchResult {
  const rng = makeRng(seed);
  const sys = new ParticleSystem(0);
  const dt = 1 / 60;
  const t0 = performance.now();

  for (let f = 0; f &lt; frames; f++) {
    if (f % burstEvery === 0) sys.burst(0, 0, burstCount, rng);
    sys.update(dt);
  }

  return {
    allocations: sys.allocations,
    ms: performance.now() - t0,
    survived: sys.activeCount,
  };
}
</code></pre>
<p>First, a heavy scenario: 3,600 frames (60 seconds at 60 FPS), spawning 60 particles every 6 frames with <code>seed = 42</code>:</p>
<pre><code class="language-text">========================================================
  Object Pool Benchmark — pooled vs unpooled particles
========================================================

### Heavy scenario
(frames=3600, burstEvery=6, burstCount=60, seed=42)

| Metric                     | Unpooled |  Pooled |
|----------------------------|----------|---------|
| Objects created            |   36,000 |     347 |
| Array allocs (per frame)   |    3,600 |       0 |
| Time (ms, median/5 runs)   |    13.38 |    5.49 |
| Survived (final count)     |      279 |     279 |
</code></pre>
<p>The allocation counts are deterministic across machines. The unpooled version creates 3,600 / 6 × 60 = 36,000 particle objects. The pooled version creates 347 objects (its high-water mark) and stops allocating, cutting object creation by two orders of magnitude.</p>
<p>Per-frame array allocations drop from 3,600 to zero, and the <code>survived</code> count matches (279 = 279), confirming both runs simulated the exact same particles.</p>
<p>Raw CPU time also drops from 13.38 ms to 5.49 ms, and cutting out the garbage removes the unpredictable 15 to 30 ms GC spikes that make a game hitch. A smooth game depends on a steady 99th-percentile frame time, even more than a high average framerate.</p>
<h3>When an object pool is useless</h3>
<p>An object pool is not a magic wand, and anyone telling you to pool everything is overselling it.</p>
<p>Modern JavaScript engines like V8 use generational garbage collection. Newly allocated objects land in the young generation (the Nursery), where a lightweight scavenger sweeps them in under a millisecond. When an object is allocated, used briefly, and discarded right away, V8 handles it with very little overhead.</p>
<p>Under low allocation rates, a pool adds extra code and bookkeeping for no real gain. Here is a light workload: 600 frames (10 seconds), spawning 8 particles once every 60 frames (1 second):</p>
<pre><code class="language-text">### Light scenario (pooling unnecessary)
(frames=600, burstEvery=60, burstCount=8, seed=42)

| Metric                     | Unpooled |  Pooled |
|----------------------------|----------|---------|
| Objects created            |       80 |       8 |
| Array allocs (per frame)   |      600 |       0 |
| Time (ms, median/5 runs)   |     0.02 |    0.01 |
| Survived (final count)     |        0 |       0 |
</code></pre>
<p>Object creation drops from 80 to 8, yet the 0.02 ms vs 0.01 ms timing difference is pure measurement noise. Depending on CPU cache locality and function inlining, the overhead of <code>acquire()</code>, <code>release()</code>, and <code>reset()</code> can even make a pooled version slightly slower than V8's scavenger.</p>
<p>Allocating 80 objects over 10 seconds does not bother V8 at all. Building an object pool for that is like setting up a coin-locked cart corral and hiring a cart crew for a corner bodega where people walk in for a loaf of bread.</p>
<p>Use an object pool when your per-frame hot path allocates hundreds or thousands of short-to-medium-lived objects per second (particles, bullets, collision manifolds, network packets, vector buffers) and Chrome DevTools shows a sawtooth heap curve with GC pauses. Skip it when allocations are sporadic, counts are small, or objects live for a long time. If the heap timeline is already flat, pooling is premature optimization.</p>
<h3>Automated Vitest verification</h3>
<p>A broken pool usually fails in one of two ways:</p>
<ol>
<li>Handing the same object to two active callers at once (shared state mutation).</li>
<li>Returning an object without resetting its fields (ghost bugs).</li>
</ol>
<p>We can lock down these invariants in Vitest:</p>
<pre><code class="language-ts">// test/pool.test.ts
import { describe, it, expect } from "vitest";
import { Pool } from "../src/pool";

interface Box {
  value: number;
}

function makePool(initial = 0) {
  return new Pool&lt;Box&gt;({
    initial,
    create: () =&gt; ({ value: 0 }),
    reset: (b) =&gt; {
      b.value = 0;
    },
  });
}

describe("Pool", () =&gt; {
  it("hands out a different object on each consecutive acquire", () =&gt; {
    const pool = makePool();
    const a = pool.acquire();
    const b = pool.acquire();
    expect(a).not.toBe(b); // never hand the same cart to two shoppers
  });

  it("returns a released object on the next acquire", () =&gt; {
    const pool = makePool();
    const a = pool.acquire();
    pool.release(a);
    const b = pool.acquire();
    expect(b).toBe(a); // same object, back in the bay and handed out again
  });

  it("resets an object on release (no leftover state)", () =&gt; {
    const pool = makePool();
    const a = pool.acquire();
    a.value = 42;
    pool.release(a);
    const b = pool.acquire();
    expect(b.value).toBe(0); // no leftover items from the previous shopper
  });

  it("grows up to the high-water mark, then stops creating", () =&gt; {
    const pool = makePool();
    const a = pool.acquire();
    const b = pool.acquire();
    const c = pool.acquire();
    expect(pool.created).toBe(3);

    pool.release(a);
    pool.release(b);
    pool.release(c);

    // take all three back: they must all come from the bay, with no new creation
    pool.acquire();
    pool.acquire();
    pool.acquire();
    expect(pool.created).toBe(3); // the water level stays put
  });
});
</code></pre>
<p>Because <code>free</code> is a LIFO array backed by <code>pop()</code> and <code>push()</code>, consecutive <code>release</code> and <code>acquire</code> calls are deterministic. The last test verifies the high-water mark: three objects in concurrent use push <code>created</code> to 3, and releasing then re-acquiring them leaves <code>created</code> at 3.</p>
<p>Next, we test <code>ParticleSystem</code> end to end to confirm that expired particles go back to the pool and get reused on the next burst:</p>
<pre><code class="language-ts">// test/particle-system.test.ts
import { describe, it, expect } from "vitest";
import { ParticleSystem } from "../src/particle-system";
import { makeRng } from "../src/rng";

describe("ParticleSystem", () =&gt; {
  it("returns a dead particle to the pool and reuses it", () =&gt; {
    const sys = new ParticleSystem(0);
    const rng = makeRng(1);

    sys.burst(0, 0, 10, rng);
    expect(sys.activeCount).toBe(10);
    expect(sys.allocations).toBe(10); // the first 10 really were created

    sys.update(100); // a huge dt: every particle's life drops below zero
    expect(sys.activeCount).toBe(0); // all of them went back to the pool

    sys.burst(0, 0, 10, rng);
    expect(sys.allocations).toBe(10); // still 10: NO new allocation, they came from the bay
  });
});
</code></pre>
<p>The second burst triggers zero new heap allocations. Ten carts went out, came back, got emptied, and went right back into circulation.</p>
<p>Finally, we verify that <code>scaleAndAdd</code> returns the exact buffer reference passed as <code>out</code>:</p>
<pre><code class="language-ts">// test/vec.test.ts
import { describe, it, expect } from "vitest";
import { scaleAndAdd } from "../src/vec";

describe("vec (in-place)", () =&gt; {
  it("updates out in place without creating a new object", () =&gt; {
    const out = { x: 0, y: 0 };
    const pos = { x: 1, y: 2 };
    const vel = { x: 0, y: 10 };
    const r = scaleAndAdd(out, pos, vel, 0.5); // out = pos + vel * 0.5

    expect(r).toBe(out); // the returned value is the very buffer we passed in
    expect(out).toEqual({ x: 1, y: 7 });
  });
});
</code></pre>
<p><code>expect(r).toBe(out)</code> confirms no new object was allocated. Across thousands of entities running at 60 FPS, keeping that contract intact prevents GC stutter.</p>
<h3>Summary</h3>
<ul>
<li>Naive <code>push({...})</code> and <code>filter(...)</code> loops pay twice: they allocate every spawned object and allocate a replacement array on every frame.</li>
<li>Check the JS Heap track in Chrome DevTools Performance; repeated climbs followed by vertical drops point to allocation churn and stop-the-world GC pauses.</li>
<li>In <code>Pool&lt;T&gt;</code>, <code>acquire()</code> hands out recycled instances from the return bay and <code>release()</code> resets and restocks them.</li>
<li>A pool only allocates up to your game's peak concurrency (the high-water mark), then stops allocating.</li>
<li>Replace <code>filter()</code> with O(1) swap-remove by copying the last item into the dead slot, calling <code>pop()</code>, and looping backward.</li>
<li>On intensive physics loops, swap immutable math helpers (<code>add</code>, <code>scale</code>) for in-place operations (<code>scaleAndAdd(out, a, b, s)</code>) and static scratch buffers.</li>
<li>Reset every field in <code>reset</code> on release so recycled objects never carry stale velocities or positions.</li>
<li>Profile before adding a pool. Generational GC handles small, short-lived allocations cheaply, so only pool when you see actual GC pressure.</li>
</ul>
<h3>Source code and live demo</h3>
<p>The full source code (pool implementation, particle system, in-place vector math, benchmark CLI, and test suite) is open source on GitHub:</p>
<blockquote>
<p>GitHub Repository: <a href="https://github.com/m2-md/object-pools-zero-allocation">github.com/m2-md/object-pools-zero-allocation</a><br />Interactive Live Demo: <a href="https://m2-md.github.io/object-pools-zero-allocation/">m2-md.github.io/object-pools-zero-allocation</a></p>
</blockquote>
<p>Run <code>npm test</code> to verify the contracts and <code>npm run bench</code> to reproduce the benchmark numbers on your own hardware.</p>
<p>Fast game loops come from knowing what the runtime allocates behind the scenes and cutting waste where it actually hurts. Keep the carts rolling back into the bay, and the exit stays clear.</p>
<h3>Canvas 2D and game architecture series</h3>
<ul>
<li>Part 1: <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas</a></li>
<li>Part 2: <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8">Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes</a></li>
<li>Part 3: <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11">Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript</a></li>
<li>Part 4 (You are here): <em>Return the Cart, Clear the Exit: Object Pools and Zero-Allocation Loops in Canvas</em></li>
<li>Up Next: <em>No Need to Wipe the Whole Table: Dirty Rectangle Rendering in Canvas 2D</em></li>
</ul>
<blockquote>
<p>⚡ <strong>Want the bundled TypeScript 2D Canvas Starter Kit &amp; Cheatsheets?</strong> Grab the <a href="https://www.buymeacoffee.com/mkare/e/599265">TS 2D Canvas Physics &amp; HiDPI Starter Kit on Buy Me a Coffee</a>.</p>
</blockquote>
<h3>About the author</h3>
<p>Hi! I'm Mustafa Morbel, a software engineer with over 17 years of experience building web technologies, game architectures, browser rendering engines, and AI workflows.</p>
<p>You can inspect all codebases, runnable demos, and test suites on my <a href="https://github.com/mkare">GitHub profile</a>.<br />For new technical guides and architecture posts, connect with me on <a href="https://www.linkedin.com/in/mustafamorbel/">LinkedIn</a> and <a href="https://x.com/mustafamorbel">X / Twitter (@mustafamorbel)</a>.</p>
<p>Have you wrestled with garbage collection pauses or written custom pooling strategies in your web games? I'd love to hear your thoughts in the comments below.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding and Building React Custom Hooks: A Practical Guide]]></title><description><![CDATA[Originally published on Medium (Becoming For Better). Read on Medium for free via Friend Link. ⚡ Get the Production-Ready React Hooks Pack Quick Takeaways…]]></description><link>https://mkare.hashnode.dev/understanding-and-building-react-custom-hooks-a-practical-guide</link><guid isPermaLink="true">https://mkare.hashnode.dev/understanding-and-building-react-custom-hooks-a-practical-guide</guid><category><![CDATA[react js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 18:19:45 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium (Becoming For Better). <a href="https://medium.com/becoming-for-better/understanding-and-building-react-custom-hooks-a-practical-guide-037ad33d1cd1?source=friends_link&amp;sk=836db934d8770a02019134bb1c213806">Read on Medium for free via Friend Link</a>.</em></p>
<p>⚡ <strong><a href="https://www.buymeacoffee.com/mkare/e/599267">Get the Production-Ready React Hooks Pack</a></strong></p>
</blockquote>
<blockquote>
<p><strong>Quick Takeaways</strong></p>
<ul>
<li><strong>Hook Rules First</strong> : Start with <code>use</code>, compose built-in hooks, stay reusable, and never return JSX.</li>
<li><strong>10 Production Patterns</strong> : Copy-ready hooks for focus, delays, window size, outside clicks, forms, fetching, debouncing, storage, media queries, and toggles.</li>
<li><strong>Build vs. Borrow</strong> : Know when to write lightweight custom hooks and when to reach for <code>usehooks.com</code> or <code>usehooks-ts.com</code>.</li>
</ul>
</blockquote>
<hr />
<p>Custom hooks in React are a powerful tool for reducing code duplication, improving code organization, and boosting overall productivity. In this article, we’ll explore what custom hooks are, how to build them, and walk through ten practical examples.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*-hF_0wuTbbgAMQyXibsmBQ.png" alt="Diagram illustrating React Custom Hooks encapsulating reusable state and side-effect logic across components" />
<em>React custom hooks extract shared stateful logic out of UI components into clean, reusable functions.</em></p>
<h3>What is a Custom Hook?</h3>
<p>A custom hook is a JavaScript function that uses one or more built-in React hooks to encapsulate reusable logic. Think of it as extracting the engine out of a component so any other component can drop it in without duplicating wiring.</p>
<h3>Rules for Creating Custom Hooks</h3>
<p>Here are the core principles to keep in mind when creating a custom hook:</p>
<ul>
<li><strong>Naming Convention</strong> : Always start the hook name with <code>use</code>. For example, a hook for managing form input can be named <code>useFormInput</code>.</li>
<li><strong>Dependencies</strong> : You can use built-in hooks like <code>useState</code>, <code>useEffect</code>, or even other custom hooks within your own.</li>
<li><strong>Reusability</strong> : A custom hook should be reusable in different components without modification.</li>
<li><strong>No JSX</strong> : Custom hooks should contain logic only. They must not return JSX or manage rendering directly.</li>
</ul>
<hr />
<h3>Useful Custom Hook Examples</h3>
<h4>1. <code>useFocus</code></h4>
<p>This hook helps programmatically focus a DOM element using <code>useRef</code> and <code>useCallback</code>.</p>
<pre><code class="language-jsx">import { useRef, useCallback } from "react";

export const useFocus = () =&gt; {
  const ref = useRef(null);

  const focusElement = useCallback(() =&gt; {
    if (ref.current) {
      ref.current.focus();
    }
  }, []);

  return [ref, focusElement];
};
</code></pre>
<hr />
<h4>2. <code>useDelay</code></h4>
<p>Returns <code>true</code> after a specified delay — useful for loading spinners or delayed content.</p>
<pre><code class="language-jsx">import { useState, useEffect } from "react";

export const useDelay = (delayTime) =&gt; {
  const [done, setDone] = useState(false);

  useEffect(() =&gt; {
    const delay = setTimeout(() =&gt; {
      setDone(true);
    }, delayTime);

    return () =&gt; clearTimeout(delay);
  }, [delayTime]);

  return done;
};
</code></pre>
<hr />
<h4>3. <code>useWindowSize</code></h4>
<p>Tracks window dimensions — perfect for responsive layouts.</p>
<pre><code class="language-jsx">import { useState, useEffect } from "react";

export const useWindowSize = () =&gt; {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() =&gt; {
    const handleResize = () =&gt; {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    window.addEventListener("resize", handleResize);

    return () =&gt; {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return windowSize;
};
</code></pre>
<hr />
<h4>4. <code>useOnClickOutside</code></h4>
<p>Detects clicks outside a specified element — great for modals and dropdowns.</p>
<pre><code class="language-jsx">import { useEffect } from "react";

export const useOnClickOutside = (ref, handler) =&gt; {
  useEffect(() =&gt; {
    const listener = (event) =&gt; {
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }
      handler(event);
    };

    document.addEventListener("mousedown", listener);
    return () =&gt; {
      document.removeEventListener("mousedown", listener);
    };
  }, [ref, handler]);
};
</code></pre>
<hr />
<h4>5. <code>useFormUpdate</code></h4>
<p>Warns users about unsaved changes before leaving the page.</p>
<pre><code class="language-jsx">import React, { useState, useEffect } from "react";

export const useFormUpdate = () =&gt; {
  const [isFormUpdated, setIsFormUpdated] = useState(false);

  useEffect(() =&gt; {
    const handleBeforeUnload = (event) =&gt; {
      if (isFormUpdated) {
        const message =
          "You have unsaved changes. " +
          "Are you sure you want to leave?";
        event.returnValue = message;
        return message;
      }
    };

    window.addEventListener(
      "beforeunload",
      handleBeforeUnload
    );

    return () =&gt; {
      window.removeEventListener(
        "beforeunload",
        handleBeforeUnload
      );
    };
  }, [isFormUpdated]);

  const handleFormUpdate = () =&gt; {
    setIsFormUpdated(true);
  };

  useEffect(() =&gt; {
    const selector =
      "form input, form select, form textarea";
    const formElements = document.querySelectorAll(selector);
    const handleFieldChange = () =&gt; {
      setIsFormUpdated(true);
    };

    formElements.forEach((element) =&gt; {
      element.addEventListener("change", handleFieldChange);
    });

    return () =&gt; {
      formElements.forEach((element) =&gt; {
        element.removeEventListener(
          "change",
          handleFieldChange
        );
      });
    };
  }, []);

  return handleFormUpdate;
};
</code></pre>
<hr />
<h4>6. <code>useFetch</code></h4>
<p>Simplifies fetching and managing API data.</p>
<pre><code class="language-jsx">import React, { useState, useEffect } from "react";

export const useFetch = (url) =&gt; {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() =&gt; {
    const fetchData = async () =&gt; {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        const result = await response.json();
        setData(result);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
};
</code></pre>
<hr />
<h4>7. <code>useDebounce</code></h4>
<p>Delays input updates — useful for search boxes and reducing API calls.</p>
<pre><code class="language-jsx">import React, { useState, useEffect } from "react";

export const useDebounce = (value, delay) =&gt; {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() =&gt; {
    const handler = setTimeout(() =&gt; {
      setDebouncedValue(value);
    }, delay);

    return () =&gt; {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
};
</code></pre>
<hr />
<h4>8. <code>useLocalStorage</code></h4>
<p>Persistent storage for data between sessions.</p>
<pre><code class="language-jsx">import React, { useState, useEffect } from "react";

export const useLocalStorage = (key, initialValue) =&gt; {
  const [storedValue, setStoredValue] = useState(() =&gt; {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  const setValue = (value) =&gt; {
    try {
      const valueToStore =
        value instanceof Function
          ? value(storedValue)
          : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(
        key,
        JSON.stringify(valueToStore)
      );
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() =&gt; {
    const handleStorageChange = () =&gt; {
      try {
        const item = window.localStorage.getItem(key);
        setStoredValue(
          item ? JSON.parse(item) : initialValue
        );
      } catch (error) {
        console.error(error);
      }
    };

    window.addEventListener("storage", handleStorageChange);

    return () =&gt; {
      window.removeEventListener(
        "storage",
        handleStorageChange
      );
    };
  }, [key, initialValue]);

  return [storedValue, setValue];
};
</code></pre>
<hr />
<h4>9. <code>useMediaQuery</code></h4>
<p>Handles responsive rendering based on screen size.</p>
<pre><code class="language-jsx">import React, { useState, useEffect } from "react";

export const useMediaQuery = (query) =&gt; {
  const [matches, setMatches] = useState(false);

  useEffect(() =&gt; {
    const mediaQuery = window.matchMedia(query);

    const handleMediaQueryChange = (event) =&gt; {
      setMatches(event.matches);
    };

    mediaQuery.addListener(handleMediaQueryChange);
    setMatches(mediaQuery.matches);

    return () =&gt; {
      mediaQuery.removeListener(handleMediaQueryChange);
    };
  }, [query]);

  return matches;
};
</code></pre>
<hr />
<h4>10. <code>useToggle</code></h4>
<p>Quick toggle between true/false states — ideal for toggles and switches.</p>
<pre><code class="language-jsx">import React, { useState } from "react";

export const useToggle = (defaultValue) =&gt; {
  const [value, setValue] = useState(defaultValue);

  function toggleValue(value) {
    setValue((currentValue) =&gt;
      typeof value === "boolean" ? value : !currentValue
    );
  }

  return [value, toggleValue];
};
</code></pre>
<hr />
<h3>Bonus: Custom Hook Libraries</h3>
<p>Instead of building every hook from scratch, you can take advantage of excellent open-source libraries:</p>
<ul>
<li><a href="https://usehooks.com"><strong>usehooks.com</strong></a> : A treasure trove of custom hooks with examples and explanations.</li>
<li><a href="https://usehooks-ts.com"><strong>usehooks-ts.com</strong></a> : Lightweight, type-safe, and written in TypeScript. Great for advanced usage.</li>
</ul>
<h3>Benefits of Using Hook Libraries</h3>
<ul>
<li><strong>Save time</strong> : Ready-made, battle-tested solutions for common UI state.</li>
<li><strong>Reduce repetition</strong> : Eliminate boilerplate across components.</li>
<li><strong>Better documentation</strong> : Learn edge-case handling from real-world examples.</li>
</ul>
<hr />
<p>Which custom hook do you find yourself copying into every new React project — or which built-in pattern still trips up your team? I'd love to hear your thoughts 🧠💬</p>
<hr />
<h3>Keep Exploring</h3>
<p>If you want to level up your frontend architecture and developer tooling, check out these related deep-dives:</p>
<ul>
<li><strong><a href="https://javascript.plainenglish.io/taming-claude-code-a-guide-to-claude-md-and-hooks-ed059879991c">Taming Claude Code: A Guide to CLAUDE.md and Hooks</a></strong> — <em>Structure AI coding workflows with deterministic project rules and lifecycle hooks.</em></li>
<li><strong><a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas</a></strong> — <em>A hands-on breakdown of simulation loops, collisions, and browser rendering.</em></li>
</ul>
<hr />
<h3>About the Author</h3>
<p>I'm <strong>Mustafa Morbel</strong> — Senior Frontend Engineer with over 17 years of experience crafting high-performance React architectures, WebGL applications, and developer tooling.</p>
<ul>
<li>Find full component examples and open-source boilerplates on my <strong><a href="https://github.com/mkare">GitHub (@mkare)</a></strong>.</li>
<li>Connect on <strong><a href="https://linkedin.com/in/mustafamorbel">LinkedIn</a></strong> and follow along on <strong><a href="https://x.com/mustafamorbel">X / Twitter (@mustafamorbel)</a></strong> for React &amp; TypeScript best practices.</li>
<li>Have a custom hook you use in every project? Share it in the comments below, and leave a few claps if you found this guide helpful!</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Taming Claude Code: A Practical Guide to CLAUDE.md and Hooks]]></title><description><![CDATA[Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link. ⚡ Get the Claude Code Production Starter Kit Quick…]]></description><link>https://mkare.hashnode.dev/taming-claude-code-a-practical-guide-to-claude-md-and-hooks</link><guid isPermaLink="true">https://mkare.hashnode.dev/taming-claude-code-a-practical-guide-to-claude-md-and-hooks</guid><category><![CDATA[AI]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 18:16:53 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium (JavaScript in Plain English). <a href="https://javascript.plainenglish.io/taming-claude-code-a-guide-to-claude-md-and-hooks-ed059879991c?source=friends_link&amp;sk=aed227294179c446ff1d1f288ac135d6">Read on Medium for free via Friend Link</a>.</em></p>
<p>⚡ <strong><a href="https://www.buymeacoffee.com/mkare/e/599264">Get the Claude Code Production Starter Kit</a></strong></p>
</blockquote>
<blockquote>
<p><strong>Quick Takeaways</strong></p>
<ul>
<li><strong>CLAUDE.md is advisory, not a hard lock:</strong> Keep it under <del>2,500 tokens (</del>100 lines), explain <em>why</em> rules exist, and split details with <code>@</code> imports or Skills.</li>
<li><strong>Hooks are deterministic guardrails:</strong> <code>PreToolUse</code> and <code>PostToolUse</code> scripts block dangerous commands, protect <code>.env</code> secrets, and auto-format every edit.</li>
<li><strong>Compounding team memory:</strong> Run <code>/init</code>, trim the bloat, and log every repeated mistake into <code>CLAUDE.md</code> + Hooks so you never repeat yourself twice.</li>
</ul>
</blockquote>
<hr />
<p>The day I first opened Claude Code, I did what any developer does — I started poking around. That’s when I noticed a file I hadn’t created: <code>CLAUDE.md</code>. I almost ignored it. I’m glad I didn’t.</p>
<p>That file turned out to be the difference between Claude writing code <em>at</em> your project and writing code <em>for</em> your project. In this piece, I want to show you exactly how — through two tools that changed how I work: <code>CLAUDE.md</code> and Hooks.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*QNGARi3VpVGjRNekc5X_nQ.jpeg" alt="Taming Claude Code with CLAUDE.md project rules and deterministic PreToolUse and PostToolUse Hooks" />
<em>CLAUDE.md gives Claude Code project context, while Hooks enforce deterministic guardrails before and after every tool call.</em></p>
<hr />
<h3>CLAUDE.md — Your Project’s Handbook</h3>
<h4>An Onboarding Guide for Claude</h4>
<p>Picture a developer joining a project for the first time. It’s their first day — they sit down at their desk, pull the repo, and start reading through the code. They’ve got some very basic questions bouncing around their head: “How do I run the build? What command runs the tests? What should I watch out for in the folder structure?” Normally, a senior developer would come over and walk them through the project — the conventions, the technical decisions, the “this is how we do things here” stuff.</p>
<p>But what if the new team member isn’t a person — it’s Claude Code?</p>
<p>That’s exactly what the <code>CLAUDE.md</code> file is for. Every time a session starts, Claude Code reads this file first. It’s an onboarding guide you hand to an AI that arrives at “zero mileage” every single time. Don’t confuse this with the classic <code>README.md</code> that’s written for humans. A README typically explains what the project does. A <code>CLAUDE.md</code> tells the AI how to <em>dive into</em> the project.</p>
<h4>Why Do We Need This File?</h4>
<p>Your project might contain dozens or hundreds of files, but Claude doesn’t need all of them to work effectively. In fact, too much irrelevant context actively hurts Claude’s performance. The goal is to point Claude to the right information at the right time.</p>
<p>If you say “build me an auth system,” Claude can do it a thousand different ways. But if your project already uses Zustand and Claude goes off building a Redux setup instead, the code works — but it doesn’t fit the fabric of your project.</p>
<p>No matter how talented Claude Code is, if it doesn’t know your project’s specific rules, technology choices, and red lines, it falls back on its own defaults.</p>
<p><code>CLAUDE.md</code> is a list of technical constraints and rules that keeps Claude aligned with your project. Thanks to this file, Claude knows which libraries you use, which coding standards you follow, and which commands are critical. Instead of producing code that clashes with the project’s architecture every time, it gives you exactly the output you expect.</p>
<h4>Quick Start: The /init Command</h4>
<p>You don’t have to write <code>CLAUDE.md</code> from scratch. Claude Code’s <code>/init</code> command automatically analyzes your project and generates a starter draft for you.</p>
<p>When this command runs, Claude scans your project’s folder structure, build system, test framework, and code patterns to create a draft. It will ask permission for every file write: you can press Enter to approve each one individually, or press Shift+Tab to cycle through permission modes — the first press switches to Auto-Accept mode (standard file read/write operations run without asking), and the second press switches to Plan mode (Claude makes no changes at all, just analyzes and presents a roadmap).</p>
<p>Rather than using the generated file as-is, delete the lines you don’t need and add rules specific to your project.</p>
<blockquote>
<p>💡 <strong>Practical Tip:</strong> Deleting is easier than writing. Trimming unnecessary lines from the <code>/init</code> output is much faster than writing everything from scratch. Remember: every line that stays in the file eats into the context window Claude needs for the actual work.</p>
</blockquote>
<h4>3 Critical Rules for Writing CLAUDE.md</h4>
<p><strong>Rule 1: Focus on “Why,” Not Just “How”</strong></p>
<p>Instead of simply dictating a technical rule, explain the engineering philosophy behind it. If Claude understands the purpose of a rule, it makes far better decisions in gray areas.</p>
<p>❌ Insufficient:</p>
<pre><code class="language-markdown">Use Zustand.
</code></pre>
<p>✅ Better:</p>
<pre><code class="language-markdown">Use Zustand for state management; we want to keep global
state minimal. For cases that don't require complex business
logic and only carry UI state, prefer React Context. Our goal
is to prevent unnecessary re-renders and keep state as close
to the relevant component as possible.
</code></pre>
<p>With this explanation, Claude starts analyzing state scope and choosing the right tool — instead of blindly wiring everything through Zustand.</p>
<p>Define the standards that shape your code structure in clear language:</p>
<pre><code class="language-markdown">## 📏 Code Standards (Strict)
- **TypeScript:** `strict` mode is on. Using `any` is an
  automatic rejection.
- **Naming:** Components use `PascalCase` (e.g.,
  `ProductCard.tsx`), Hooks use `camelCase` (`useCart.ts`).
- **Functions:** Prefer `arrow functions` and `functional
  programming` principles wherever possible.
</code></pre>
<p><strong>Rule 2: Draw Operational Boundaries</strong></p>
<p>Claude Code’s biggest differentiator is terminal access. But this power, left unchecked, can pollute your project. To prevent Claude from “guessing” its way forward, make your operational workflow explicit.</p>
<pre><code class="language-markdown">## Verification Protocol
1. Implement the change.
2. Start the app with the stack-specific command
   (e.g., `next dev`, `nx serve`, `npm run dev`).
3. Test critical UI paths with Playwright MCP.
4. If no errors, proceed to the commit stage.
</code></pre>
<p>In monorepo setups, for instance, Claude sometimes gets confused about which package goes where. It might install a package meant for <code>apps/web</code> inside <code>packages/ui</code> by mistake. Prevent this by making the rules explicit:</p>
<pre><code class="language-markdown">## Package Management Rules
- Before adding a new dependency, always check if it already
  exists in `@repo/shared`.
- Always use the `--filter` flag when adding dependencies
  (e.g., `pnpm add lodash --filter web`).
- Never add packages to the root directory; always target
  the relevant workspace.
</code></pre>
<blockquote>
<p>⚠️ <strong>A Critical Distinction You Should Know: Advice vs. Enforcement</strong></p>
<p><code>CLAUDE.md</code> instructions are “advisory” in nature. Anthropic’s official documentation states this clearly: Claude processes this file as context, but doesn’t feel obligated to follow it like a hard rule every time. The system wraps this file with the caveat: <em>“This context may or may not be relevant to your tasks.”</em></p>
<p>This means Claude can ignore certain rules — especially if the file is too long. That’s why these two tools serve different purposes:</p>
<ul>
<li><strong>CLAUDE.md (Nature: Advisory)</strong> — Use for guidelines, coding preferences, and architectural decisions.</li>
<li><strong>Hooks (Nature: Deterministic — Always runs)</strong> — Use for hard rules like running lint, formatting code, and blocking dangerous commands.</li>
</ul>
<p><em>For operations like running lint, applying formatting, or blocking dangerous commands, trust Hooks — not CLAUDE.md.</em></p>
</blockquote>
<p><strong>Rule 3: Keep It a Living Document (Feedback Loop)</strong></p>
<p>Writing your <code>CLAUDE.md</code> once and shelving it is one of the most common mistakes. This file should be a living knowledge base that breathes alongside your project, updated with every lesson learned.</p>
<p><code>CLAUDE.md</code> is not a static file. If you find yourself correcting the same Claude mistake twice, add the rule that prevents it to the file immediately. As Boris Cherny (creator of Claude Code and Head of Claude Code) puts it: “If Claude does something wrong, we write it into CLAUDE.md so it never does it again.” This creates a feedback loop where the system improves itself.</p>
<p>Boris takes this a step further: his team tags teammates’ PRs with <code>@.claude</code>, automatically feeding lessons from code reviews into <code>CLAUDE.md</code>. He calls this “Compounding Engineering.” Every PR review becomes permanent team knowledge.</p>
<pre><code class="language-markdown">## 🚫 "Don't" List (Lessons Learned)
- **Styling:** Don't create SCSS/CSS files — handle all
  design with Tailwind utility classes.
- **Debugging:** Don't use `console.log` — use the
  centralized `logger` service and `Error Boundary` patterns.
- **Security:** Never hardcode API URLs — always access
  them through `.env` variables.
</code></pre>
<p>The most practical way to add a rule on the fly: just tell Claude directly.</p>
<pre><code class="language-text">"Add to the CLAUDE.md file that we always use TypeScript
strict mode in this project from now on."
</code></pre>
<p>Claude opens the file in the background, adds the rule automatically, and confirms the operation.</p>
<p>There’s an even faster route: in the terminal, anything starting with <code>#</code> gets saved directly to project memory (<code>CLAUDE.md</code>) as a note — without Claude generating a response at all:</p>
<pre><code class="language-bash">#Always use bun in this project, not npm
</code></pre>
<p>When you hit Enter, Claude asks whether this note should be saved at the project level (the team’s <code>CLAUDE.md</code>) or at the personal level (<code>~/.claude/CLAUDE.md</code>). Something you say once, you never have to say again.</p>
<blockquote>
<p>✅ <strong>Tip:</strong> Add emphasis markers like <code>IMPORTANT:</code> or <code>YOU MUST</code> before critical rules. Official documentation confirms this technique improves Claude’s compliance rate.</p>
</blockquote>
<h4>Referencing Files with @</h4>
<p>The most practical way to point Claude at the right information is the <code>@</code> symbol. It works in two different contexts:</p>
<p><strong>During conversation:</strong> When you want Claude to look at a specific file or directory, write the file path with <code>@</code>:</p>
<pre><code class="language-text">How does the auth system work? @auth
</code></pre>
<p>Claude lists the relevant files, adds the ones you select to the current conversation context. Instead of loading your entire project into context, you’ve pulled in just the file you need.</p>
<p><strong>Inside CLAUDE.md:</strong> You can use the same syntax within your <code>CLAUDE.md</code> file. Files referenced this way are automatically included in every request:</p>
<pre><code class="language-markdown">The database schema is defined in @prisma/schema.prisma.
Refer to this file when you need to understand the
database structure.
</code></pre>
<p>This way, Claude can answer questions about the schema instantly without having to search for the file each time.</p>
<h4>File Locations and Hierarchy</h4>
<p><code>CLAUDE.md</code> doesn’t have to live in just one place. Claude Code loads and merges these files hierarchically:</p>
<ul>
<li><strong><code>~/.claude/CLAUDE.md</code></strong> (Scope: All projects) — For personal preferences and editor settings.</li>
<li><strong><code>./CLAUDE.md</code></strong> (Scope: This project / committed to git) — For team standards and shared rules.</li>
<li><strong><code>./CLAUDE.local.md</code></strong> (Scope: This project / added to <code>.gitignore</code>) — For your personal project notes only.</li>
<li><strong><code>./frontend/CLAUDE.md</code></strong> (Scope: Frontend directory only) — For rules specific to a subdirectory.</li>
</ul>
<p>Subdirectory-level <code>CLAUDE.md</code> files are especially powerful in large projects. You can define separate rules for the <code>frontend/</code> directory and different rules for <code>backend/</code>. Claude automatically loads the relevant file only when working in that directory — your main file doesn’t get bloated for no reason.</p>
<h4>Modular Structure</h4>
<p>As your <code>CLAUDE.md</code> grows, you can import other files using the <code>@</code> syntax. This is one of the most effective ways to preserve token economy:</p>
<pre><code class="language-markdown"># CLAUDE.md

## Project Overview
Next.js + Turborepo monorepo. Details: @README.md

## Commands
Available npm scripts: @package.json

## Detailed Rules
- Git workflow: @docs/git-rules.md
- API standards: @docs/api-conventions.md
- Personal preferences: @~/.claude/my-preferences.md
</code></pre>
<p>Your main file stays short and focused while detailed rules live in separate files. Claude only reads them when needed.</p>
<p>Taking it one step further: you can move instructions that are rarely needed but critical for specific workflows into Skills (<code>.claude/skills/&lt;name&gt;/SKILL.md</code>). Unlike <code>CLAUDE.md</code>, Skills aren’t loaded at every session — they’re only invoked when needed. That means token savings on every conversation.</p>
<h4>Token Economy: The Math of Keeping It Short</h4>
<p>Boris Cherny’s (creator of Claude Code) team’s <code>CLAUDE.md</code> file is roughly 2,500 tokens — about 100 lines. The team that actually builds Claude Code keeps theirs this short.</p>
<p>The reason is simple: this file gets loaded into Claude’s context window at the start of every session. The longer the file, the less room Claude has for the actual work. An even more serious problem: in overly long files, Claude starts missing important rules altogether.</p>
<blockquote>
<p>📌 <strong>From the Official Docs:</strong> <em>“If Claude keeps making mistakes despite a rule being in CLAUDE.md, the file is probably too long and important rules are getting lost in the noise.”</em></p>
</blockquote>
<p>For every rule, ask yourself: “If I delete this line, will Claude make mistakes?” If the answer is no, delete it.</p>
<ul>
<li>Don’t write things Claude already does correctly (e.g., “Use TypeScript” — Claude already knows this)</li>
<li>Write the mistakes Claude repeatedly makes <em>in your specific project</em>, not general concepts</li>
<li>Move rarely needed instructions to separate files with <code>@</code> or into Skills</li>
<li>Commit the file to git — let your team contribute; the value compounds over time</li>
</ul>
<blockquote>
<p>ℹ️ <strong>How to use the templates below:</strong> These templates are intentionally comprehensive to show what <em>could</em> go into a <code>CLAUDE.md</code> for each stack. Don’t copy them as-is — pick what fits your project and use <code>@</code> to move details into sub-files, keeping the main file within the 2,500-token limit.</p>
</blockquote>
<h4>Example CLAUDE.md Templates</h4>
<p><strong>Template optimized for a Next.js + Turborepo project:</strong></p>
<pre><code class="language-markdown">## Stack &amp; Architecture
- Monorepo: Turborepo (Remote Caching active).
- Frontend: Next.js 15 (App Router), React 19, Tailwind.
- Backend: NestJS, GraphQL (Code-first), PostgreSQL.
- State: Zustand (Global), Context (UI), TanStack Query.
- Shared: @repo/ui (components), @repo/utils (helpers).

## Code Standards (NON-NEGOTIABLE)
1. Next.js Patterns: Server Components by default. Use
   'use client' only on lowest-level interactive leaves.
2. State Strategy:
   - Server data: TanStack Query. NEVER use Zustand.
   - Global auth/settings: Zustand.
   - Form/UI toggle: local state or Context.
3. GraphQL: Fragment Colocation per component.
4. Turborepo: Strict apps/ vs packages/ boundary.
5. TS: no any. type &gt; interface. Errors: Result pattern.

## Verification Protocol
1. Implement: Write the code.
2. Verify: turbo lint &amp;&amp; turbo build --filter=[APP_NAME]
3. Test: If critical change, run Playwright MCP UI test.
4. Commit: Only git commit after verification passes.

## Git Workflow
- Branch: feat/PROJECT-{ID}_desc or fix/PROJECT-{ID}_desc
- Commit: Conventional Commits (feat:, fix:, refactor:)
- Rule: Commits without a Ticket ID will not be accepted.

## Claude's Role
- Role: Principal Full-Stack Architect (10+ years).
- IMPORTANT: Avoid unnecessary abstraction. Optimize for
  OWASP security + LCP/CLS.
</code></pre>
<p><strong>Template optimized for an Angular &amp; NX Monorepo project:</strong></p>
<pre><code class="language-markdown">## Stack &amp; Architecture (Angular &amp; NX)
- Monorepo: NX (Integrated or Package-based).
- Frontend: Angular 19 (Standalone, Signals-based).
- State: NgRx Signal Store, component-store, Signal (UI).
- Backend: NestJS, GraphQL (Code-first), PostgreSQL.
- Shared: @shared/ui, @shared/util, @shared/data-access.

## Code Standards (NON-NEGOTIABLE)
1. Signals-First: Use Signals in new components/services.
   OnPush is mandatory. Do not use markForCheck().
2. NX Patterns: Under libs/, use Type (ui/data-access/
   feature/util) and Scope (shared/admin/auth) tags.
   No imports outside @repo/*.
3. State: Server-&gt;NgRx Effects, Global-&gt;NgRx Signal Store
   (Facade preserved), Local-&gt;signal() or component-store.
4. RxJS vs Signals: WebSocket/polling-&gt;RxJS; UI-&gt;Signals.
5. Styling: Tailwind+DaisyUI. Global SCSS for vars only.

## Operational Safety (via Hooks)
- IMPORTANT: Run nx lint --fix &amp;&amp; nx format:write after
  every change.
- Code that fails nx type-check cannot be committed.
- YOU MUST: Use nx generate for new components/services.
  No manual file creation.

## Verification Protocol
1. Implement -&gt; 2. nx lint ${project} &amp;&amp; nx test ${project}
3. nx serve (if UI change) -&gt; 4. Playwright MCP E2E
5. Commit: Only if affected:build succeeds.

## Claude's Role
- Role: Principal Angular Architect (10+ years).
- Anti-Pattern Rejection: any usage, skipping Facade,
  non-Standalone components.
- Do not add deps that break NX dep-graph rules.
</code></pre>
<p><strong>Template optimized for a MERN Stack project:</strong></p>
<pre><code class="language-markdown">## Stack &amp; Architecture (MERN)
- Database: MongoDB (Mongoose).
- Backend: Node.js (Express), JWT Auth.
- Frontend: React 19 (Vite), Redux Toolkit + RTK Query.
- Style: Tailwind CSS + Headless UI.
- Validation: Zod (shared schemas across FE + BE).

## Code Standards (NON-NEGOTIABLE)
1. Controller-Service Pattern:
   Route -&gt; Controller (Req/Res) -&gt; Service -&gt; Model (DB).
   Never put business logic in routes.
2. API Standards: RESTful with consistent JSON.
   HTTP status: 400/401/403/404/500.
3. Security (IMPORTANT): Validate all inputs with Zod.
   Passwords -&gt; bcrypt. NoSQL -&gt; Mongoose sanitizer.
4. Frontend State: Server -&gt; RTK Query. UI -&gt; Redux slice.
5. Env Vars: Hardcoding MONGODB_URI/JWT_SECRET is
   forbidden. Access via config/.

## Operational Safety
- Pre-commit: Require npm run lint &amp;&amp; npm run build.
- When a Model changes, update the matching Zod schema.
- Don't console.log inside try-catch; route to the
  centralized error handler.

## Verification Protocol
1. Implement -&gt; 2. API test (Postman/Curl)
3. npm run dev + Chrome DevTools error check
4. Playwright MCP E2E test for critical flows
5. Commit with Conventional Commits.

## Claude's Role
- Role: Senior MERN Developer (10+ years).
- Security First: Review code through the lens of
  "how would a hacker exploit this?"
- DRY: Move repeated code into helpers/utilities.
</code></pre>
<h4>Final Note: Not Perfect — Just Working</h4>
<p>Trying to write the “perfect” <code>CLAUDE.md</code> is one of the most common traps. This file doesn’t need to be perfect — it needs to be useful.</p>
<p>To get started: run <code>/init</code>, delete the unnecessary lines, and add a few rules specific to your project. Then put Claude to work. Whenever you catch yourself correcting the same mistake twice, add the rule that prevents it to the file. Over time, <code>CLAUDE.md</code> becomes your team’s collective memory.</p>
<p><strong>Here’s what I wish someone had told me before I spent a week figuring this out:</strong></p>
<ul>
<li>Start with <code>/init</code> → Shift+Tab to select mode → delete the unnecessary → add project-specific rules</li>
<li>Use <code>@</code> to reference files both in conversation and inside <code>CLAUDE.md</code></li>
<li>Use <code>#</code> for quick notes → Claude writes to memory without generating a response</li>
<li>Keep it modular → respect the ~2,500 token limit, use Skills for token savings</li>
<li>Commit to git → share with your team → let it grow over time</li>
<li>Use Hooks for mandatory rules — <code>CLAUDE.md</code> is advisory, Hooks are deterministic</li>
</ul>
<hr />
<h3>HOOKS — Automating Your Engineering Reflexes</h3>
<h4>Enforcement</h4>
<p>We set the project’s rules by preparing the <code>CLAUDE.md</code> file. But a rule being written down doesn’t mean it will always be followed. Expecting a speed-focused agent like Claude to comply 100% of the time would be a bit optimistic.</p>
<p>This is where Hooks come in. Hooks are automated guardrails that run before (Pre) or after (Post) Claude takes action, protecting the project’s quality standards.</p>
<p>When Claude writes code or runs a terminal command, the system quietly checks in the background: “Does this operation meet our standards?”</p>
<p>Hooks block Claude: Claude cannot move to the next step until a hook completes. Claude Code currently supports 18+ different hook events — <code>PreToolUse</code> and <code>PostToolUse</code> alongside <code>Notification</code>, <code>Stop</code>, <code>SubagentStop</code>, <code>SessionStart</code>, <code>SessionEnd</code>, and more. In this article, we’ll focus on the two most critical ones: Pre and Post.</p>
<p>The default timeout for hooks is 10 minutes. If a hook doesn’t complete within that window, it gets skipped and Claude continues. This timeout is customizable per hook.</p>
<blockquote>
<p><strong>GitHub — <a href="https://github.com/karanb192/claude-code-hooks">karanb192/claude-code-hooks</a>:</strong> 🪝 <em>A growing collection of useful Claude Code hooks. Copy, paste, customize.</em></p>
</blockquote>
<p>This repo contains pre-written hook scripts designed to make your Claude Code experience safer and more controlled.</p>
<h4>Setup</h4>
<p>Instead of writing everything from scratch, here’s a step-by-step walkthrough for installing and using the tools from this repo.</p>
<p><strong>Step 1: Prerequisites</strong></p>
<p>The hooks in this repo are written in Node.js. I’m sure you already have it installed.</p>
<p><strong>Step 2: Download the Repo</strong></p>
<p>You need to download these scripts to a permanent location Claude can access. The <code>.claude</code> folder is usually the cleanest spot.</p>
<p>Open your terminal and run these commands in order:</p>
<pre><code class="language-bash"># 1. Navigate to the Claude settings folder
mkdir -p ~/.claude/hooks
cd ~/.claude/hooks

# 2. Clone the repo here
git clone https://github.com/karanb192/claude-code-hooks.git .
</code></pre>
<p>The scripts are now sitting at <code>~/.claude/hooks/</code> on your machine.</p>
<p><strong>Step 3: Configure Claude’s Settings (settings.json)</strong></p>
<p>Now we need to tell Claude Code: “Hey, check in with these scripts before you do anything.”</p>
<p>Open <code>~/.claude/settings.json</code> (create it if it doesn’t exist).</p>
<p>Paste the following JSON block inside. This configuration activates the three most critical protections from the repo:</p>
<pre><code class="language-json">{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command":
            "node ~/.claude/hooks/block-dangerous-commands.js"
        }]
      },
      {
        "matcher": "Read|Edit|Write|Bash",
        "hooks": [{
          "type": "command",
          "command":
            "node ~/.claude/hooks/protect-secrets.js"
        }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{
          "type": "command",
          "command":
            "node ~/.claude/hooks/auto-stage.js"
        }]
      }
    ]
  }
}
</code></pre>
<blockquote>
<p><strong>Note:</strong> When you clone the repo, sometimes nested folders can appear (like <code>hooks/hooks/</code>). Double-check the exact path of your scripts (run <code>ls ~/.claude/hooks</code> to verify). If the scripts are directly there, the paths above are correct.</p>
</blockquote>
<p>Here’s what each of the three scripts does:</p>
<ul>
<li><strong><code>block-dangerous-commands.js</code> (Danger Blocker)</strong> : If Claude accidentally tries to run <code>rm -rf /</code>, <code>mkfs</code> (disk format), or any command that could lock up your machine, this script steps in and blocks the operation. For you: it eliminates the fear of “what if it deletes my entire project?”</li>
<li><strong><code>protect-secrets.js</code> (Secret File Protection)</strong> : If Claude tries to read or print sensitive files like <code>.env</code>, <code>id_rsa</code> (SSH keys), or AWS credential files to the terminal (e.g., <code>cat .env</code>), this blocks it. For you: it prevents API keys from accidentally leaking into logs or chat history.</li>
<li><strong><code>auto-stage.js</code> (Automatic Git Add)</strong> : When Claude modifies a file, this automatically runs <code>git add &lt;file&gt;</code> as soon as the operation completes. When you run <code>git status</code>, you’ll see changes already “staged” and ready — committing becomes effortless.</li>
</ul>
<p><strong>Final Step: Testing It</strong></p>
<p>After the setup, launch Claude Code (<code>claude</code>) in your terminal and run this test:</p>
<p><strong>You:</strong> “Show me the contents of my .env file.” (If no <code>.env</code> exists, say “create a dummy .env and read it.”)</p>
<p><strong>Expected result:</strong> Normally Claude would read it instantly. Now the hook kicks in and Claude responds with something like: <em>“Access denied by hook: protect-secrets.js prevented reading sensitive file.”</em></p>
<p><strong>You:</strong> “Run the command <code>rm -rf /</code> in the terminal.”</p>
<p><strong>Expected result:</strong> The hook steps in and says <em>“This command is too dangerous, permission denied.”</em></p>
<h4>Writing Your Own Engineering Reflexes</h4>
<p>Every project has its own red lines. If you want to automate not just security but code quality as well, you’ll need to write your own hooks.</p>
<p><strong>Anti-Pattern Detector (PreToolUse)</strong></p>
<p>Claude sometimes takes the fastest route and punches through your project’s architectural rules. In a Next.js project, for example, it might forget the <code>use client</code> directive or try to use a library you’ve banned. We can catch this at the <code>PreToolUse</code> stage.</p>
<p>The following script scans the content when Claude tries to write a file and blocks the operation if it finds <code>console.log</code>:</p>
<pre><code class="language-js">// ~/.claude/hooks/check-patterns.js
const fs = require('fs');

// Read the data coming from Claude
const data = JSON.parse(fs.readFileSync(0, 'utf-8'));
const toolInput = data.tool_input;

// We only care about file write or edit operations
if (data.tool_name === 'Write' || data.tool_name === 'Edit') {
  const content =
    toolInput.content || toolInput.new_content || "";

  // Rule: console.log is banned!
  if (content.includes('console.log')) {
    console.log(JSON.stringify({
      decision: "block",
      reason:
        "⚠️ Standard Violation: console.log detected " +
        "in code. Please use the project's logger service."
    }));
    process.exit(0);
  }
}

console.log(JSON.stringify({ decision: "approve" }));
</code></pre>
<p><strong>Linter &amp; Formatter</strong></p>
<p>Claude sometimes writes the code but misses the project’s formatting rules. Don’t waste time telling it “format the code” every single time. The moment Claude saves a file (<code>PostToolUse</code>), let’s run Prettier or ESLint in the background to bring the code in line with project standards.</p>
<p>Create a file at <code>~/.claude/hooks/auto-format.js</code> and add this logic:</p>
<pre><code class="language-js">/**
 * Auto-Format Hook: Runs every time Claude edits
 * a file (PostToolUse).
 */
const { execSync } = require('child_process');
const fs = require('fs');

const chunks = [];
process.stdin.on('data', chunk =&gt; chunks.push(chunk));
process.stdin.on('end', () =&gt; {
  const input = JSON.parse(Buffer.concat(chunks).toString());
  const file =
    input.tool_input.path || input.tool_input.file_path;

  // Only run on relevant file types
  if (
    file &amp;&amp;
    (file.endsWith('.ts') ||
      file.endsWith('.tsx') ||
      file.endsWith('.js'))
  ) {
    try {
      // Trigger prettier in the project directory
      execSync(`npx prettier --write "${file}"`, {
        stdio: 'ignore',
        cwd: input.cwd
      });
    } catch (e) { /* Fail silently */ }
  }
  process.exit(0);
});
</code></pre>
<p><strong>DevOps Guard (Production Protection)</strong></p>
<p>Claude having terminal access is a superpower, but if it hallucinates and tries to push to the <code>main</code> branch uncontrolled, or accidentally runs a command that affects the production environment, things get messy fast.</p>
<p>This hook catches patterns like “prod,” “main,” and “DROP DATABASE,” stops Claude in its tracks, and asks for your explicit approval.</p>
<p>Create the file <code>~/.claude/hooks/production-guard.js</code>:</p>
<pre><code class="language-js">/**
 * DevOps Guard: Requests explicit "APPROVAL" from
 * the user for dangerous commands.
 */
const chunks = [];
process.stdin.on('data', chunk =&gt; chunks.push(chunk));
process.stdin.on('end', () =&gt; {
  const input = JSON.parse(Buffer.concat(chunks).toString());
  const cmd = input.tool_input.command || "";

  const dangerousPatterns = [
    /git push.*(main|master)/i, // Push to main branch
    /DROP DATABASE/i,           // Database deletion
    /kubectl.*delete.*prod/i    // K8s prod deletion
  ];

  if (dangerousPatterns.some(p =&gt; p.test(cmd))) {
    console.log(JSON.stringify({
      hookSpecificOutput: {
        hookEventName: "PreToolUse",
        permissionDecision: "ask", // Ask the user!
        permissionDecisionReason:
          "⚠️ CRITICAL WARNING: Command may affect " +
          `Production or Main branch: '${cmd}'`
      }
    }));
  } else {
    process.exit(0);
  }
});
</code></pre>
<h4>Final Configuration: settings.json</h4>
<p>To manage all these scripts from one place, update your <code>~/.claude/settings.json</code> as follows. Order matters here: format the code first, then stage it.</p>
<pre><code class="language-json">{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command":
              "node ~/.claude/hooks/block-dangerous-commands.js"
          },
          {
            "type": "command",
            "command":
              "node ~/.claude/hooks/production-guard.js"
          }
        ]
      },
      {
        "matcher": "Read|Edit|Write|Bash",
        "hooks": [{
          "type": "command",
          "command":
            "node ~/.claude/hooks/protect-secrets.js"
        }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command":
              "node ~/.claude/hooks/auto-format.js"
          },
          {
            "type": "command",
            "command":
              "node ~/.claude/hooks/auto-stage.js"
          }
        ]
      }
    ]
  }
}
</code></pre>
<hr />
<h3>Conclusion: Advice + Enforcement = Control</h3>
<p>In this article, we covered two tools and saw how they complement each other.</p>
<p><code>CLAUDE.md</code> answers the question “what should be done”: the project’s architecture, coding standards, red lines. But it’s advisory in nature — Claude sometimes listens, sometimes does its own thing.</p>
<p>Hooks answer the question “how do we enforce it”: no matter what Claude does, deterministic checks run in the background. Code gets formatted, dangerous commands get blocked, changes get automatically staged.</p>
<p>When you set up both together, what you get is a self-regulating system — one where you no longer need to say “do this too, check that too” every single time.</p>
<p>To get started: run <code>/init</code>, add a few rules, set up the three core hooks. The first time Claude makes a mistake, write that mistake into the file. Over time, <code>CLAUDE.md</code> becomes your team’s collective memory, and Hooks become its reflexes.</p>
<p>Which rule or hook are you adding to your workflow first — blocking dangerous commands, protecting <code>.env</code> files, or auto-formatting every edit? I'd love to hear how you're taming Claude Code in your own projects 🧠💬</p>
<hr />
<h3>🚀 Keep Exploring</h3>
<p>If you found this deep-dive valuable, explore more Claude Code and AI engineering breakdowns:</p>
<ul>
<li>📌 <strong><a href="https://ai.plainenglish.io/claude-fable-5-2-changed-the-rules-1-280-updates-just-broke-your-defaults-efb2ca1733e2">Claude Fable 5.2 Changed the Rules: 1,280+ Updates Just Broke Your Defaults</a></strong> — <em>How shifting Claude defaults impact your agentic workflows and configuration baselines.</em></li>
<li>📌 <strong><a href="https://medium.com/t%C3%BCrkiye/claude-code-ultraplan-terminali-kilitleyen-plan-moduna-son-0744cbfa8035">Claude Code Ultraplan: Terminali Kilitleyen Plan Moduna Son (TR)</a></strong> — <em>Offload agentic planning into the cloud while keeping local developer velocity intact.</em></li>
<li>📦 <strong><a href="https://github.com/karanb192/claude-code-hooks">karanb192/claude-code-hooks on GitHub</a></strong> — <em>Ready-to-use PreToolUse and PostToolUse Node.js hook scripts featured in this guide.</em></li>
</ul>
<hr />
<h3>👋 About the Author</h3>
<p>I'm <strong>Mustafa Morbel</strong> — Senior Frontend Engineer with over 17 years of experience building modern frontend architectures, WebGL/creative applications, and agentic developer workflows.</p>
<ul>
<li>Explore working repositories, hooks, and benchmarks on my <strong><a href="https://github.com/mkare">GitHub (@mkare)</a></strong>.</li>
<li>Connect on <strong><a href="https://linkedin.com/in/mustafamorbel">LinkedIn</a></strong> and follow along on <strong><a href="https://x.com/mustafamorbel">X / Twitter (@mustafamorbel)</a></strong> for ongoing engineering notes.</li>
<li>Have questions or ideas on hook automation? Drop a comment below, and feel free to leave a few claps 👏 if this helped your setup!</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[HTML Native Dialog Component in React with Tailwind CSS]]></title><description><![CDATA[Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link. ⚡ Get the Production-Ready React Hooks Pack Building…]]></description><link>https://mkare.hashnode.dev/html-native-dialog-component-in-react-with-tailwind-css</link><guid isPermaLink="true">https://mkare.hashnode.dev/html-native-dialog-component-in-react-with-tailwind-css</guid><category><![CDATA[react js]]></category><category><![CDATA[HTML]]></category><category><![CDATA[Tailwind CSS]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 14:38:12 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium (JavaScript in Plain English). <a href="https://javascript.plainenglish.io/html-native-dialog-component-in-react-with-tailwind-css-2b23356ef036?sk=c6390da45cb7102d6e3a5366316603ef">Read on Medium for free via Friend Link</a>.</em></p>
<p>⚡ <strong><a href="https://www.buymeacoffee.com/mkare/e/599267">Get the Production-Ready React Hooks Pack</a></strong></p>
</blockquote>
<p><img src="https://cdn-images-1.medium.com/max/800/1*zvMYB8byCP3ymRmerMFg_Q.png" alt="Native HTML dialog modal component in React styled with Tailwind CSS showing backdrop and form controls" /></p>
<p><em>Building an interactive, backdrop-ready modal in React using the native HTML <code>&lt;dialog&gt;</code> element and Tailwind CSS.</em></p>
<h3>Quick Takeaways</h3>
<ul>
<li><strong>Zero modal dependencies</strong> : The native <code>&lt;dialog&gt;</code> element gives you <code>showModal()</code>, <code>close()</code>, top-layer rendering, and Escape-key dismissal out of the box.</li>
<li><strong>Click-outside and lifecycle events</strong> : Pair <code>getBoundingClientRect()</code> with native <code>close</code> and <code>cancel</code> events to handle backdrop clicks and state sync cleanly.</li>
<li><strong>Tailwind CSS animations</strong> : Combine <code>open:</code> and <code>backdrop:</code> variants with custom <code>@keyframes</code> in <code>tailwind.config.js</code> for smooth fade-in transitions.</li>
</ul>
<hr />
<p>Building a modal in React usually starts with installing a third-party library. Yet modern browsers already ship a powerful primitive built right into HTML: the <code>&lt;dialog&gt;</code> element.</p>
<p>In this guide, we will walk through creating an interactive HTML Native Dialog component broken into four practical parts: native <code>&lt;dialog&gt;</code> basics, backdrop clicks and events, CSS and Tailwind animations, and the complete React TypeScript component.</p>
<hr />
<h3>1. Native HTML <code>&lt;dialog&gt;</code> Basics</h3>
<p>At its core, <code>&lt;dialog&gt;</code> handles top-layer stacking, focus trapping, and form integration without extra JavaScript plumbing. Here is a minimal HTML example with a trigger button, a dialog form, and <code>showModal()</code> / <code>close()</code> handlers:</p>
<pre><code class="language-html">&lt;button
  type="button"
  onclick="openDialog()"
&gt;
  Open Dialog
&lt;/button&gt;

&lt;dialog id="nativeDialog"&gt;
  &lt;form method="dialog"&gt;
    &lt;input
      type="text"
      placeholder="Enter your name"
    /&gt;
    &lt;button type="submit"&gt;Submit&lt;/button&gt;
    &lt;button
      formmethod="dialog"
      type="reset"
      onclick="closeDialog()"
    &gt;
      Cancel
    &lt;/button&gt;
  &lt;/form&gt;
&lt;/dialog&gt;

&lt;script&gt;
  function openDialog() {
    const dialog = document.getElementById(
      "nativeDialog"
    );
    dialog.showModal();
  }

  function closeDialog() {
    const dialog = document.getElementById(
      "nativeDialog"
    );
    dialog.close();
  }
&lt;/script&gt;
</code></pre>
<p>The <code>dialog</code> box contains a form with a name input and two buttons for submission and cancellation. Calling <code>showModal()</code> displays the dialog in the browser's top layer with a built-in backdrop.</p>
<hr />
<h3>2. Handling Events and Backdrop Clicks</h3>
<p>Closing the modal with the Escape key comes included by default when using <code>&lt;dialog&gt;</code>. You can also listen for clicks directly on the <code>dialog</code> element to close it when the user clicks the backdrop:</p>
<pre><code class="language-ts">const dialog = document.querySelector("dialog");
dialog?.addEventListener("click", (e: MouseEvent) =&gt; {
  if (e.target === dialog) {
    // close the dialog
    dialog.close();
  }
});
</code></pre>
<p>To react when the modal finishes closing, attach a listener for the native <code>close</code> event:</p>
<pre><code class="language-ts">const dialog = document.querySelector("dialog");
dialog?.addEventListener("close", () =&gt; {
  console.log("dialog closed");
});
</code></pre>
<p>Note that the <code>close</code> event fires when the dialog closes normally, whereas pressing Escape triggers a <code>cancel</code> event first.</p>
<p>What if your dialog contains nested elements or padding that makes <code>e.target === dialog</code> unreliable? You can calculate the dialog's bounding box with <code>getBoundingClientRect()</code> and close it whenever a click lands outside those coordinates:</p>
<pre><code class="language-ts">const dialog = document.querySelector("dialog");
dialog?.addEventListener("click", (e: MouseEvent) =&gt; {
  const rect = dialog.getBoundingClientRect();
  if (
    e.clientX &lt; rect.left ||
    e.clientX &gt; rect.right ||
    e.clientY &lt; rect.top ||
    e.clientY &gt; rect.bottom
  ) {
    dialog.close();
  }
});
</code></pre>
<p>This approach checks the pointer coordinates against the dialog's rendered rectangle, ensuring clicks outside the modal surface always dismiss it cleanly.</p>
<hr />
<h3>3. Animating <code>&lt;dialog&gt;</code> and <code>::backdrop</code> in CSS &amp; Tailwind</h3>
<p>By default, a native <code>&lt;dialog&gt;</code> snaps open and shut without transitions. You can add a smooth fade-in in plain CSS by targeting <code>dialog[open]</code> and <code>dialog[open]::backdrop</code>:</p>
<pre><code class="language-css">@keyframes fade-in {
  0% { opacity: 0; }
  100% { opacity: 1; }
}

dialog {
  /* Initially invisible */
  opacity: 0;
}

dialog[open] {
  opacity: 1;
  animation: fade-in 0.5s ease-in-out;
}

dialog::backdrop {
  /* Styles for the backdrop */
}

dialog[open]::backdrop {
  opacity: 1;
  animation: fade-in 0.5s ease-in-out;
}
</code></pre>
<h4>Add Animation to Tailwind CSS</h4>
<p>To bring that same transition into Tailwind CSS, register the <code>fade-in</code> keyframe and animation inside your <code>tailwind.config.js</code> file:</p>
<pre><code class="language-js">module.exports = {
  // ...
  theme: {
    extend: {
      keyframes: {
        "fade-in": {
          "0%": { opacity: "0%" },
          "100%": { opacity: "100%" },
        },
      },
      animation: {
        "fade-in": "fade-in 0.5s ease-in-out",
      },
    },
  },
};
</code></pre>
<p>Once configured, you can apply the effect to both the dialog and its backdrop using Tailwind's <code>open:</code> and <code>backdrop:</code> modifiers:</p>
<pre><code class="language-html">&lt;dialog
  class="
    open:animate-fade-in
    open:backdrop:animate-fade-in
  "
&gt;
  ...
&lt;/dialog&gt;
</code></pre>
<hr />
<h3>4. HTML Native Dialog Component in React with Tailwind CSS</h3>
<p>Now let's combine <code>useRef</code>, <code>useEffect</code>, native <code>&lt;dialog&gt;</code> events, and Tailwind CSS into a complete React TypeScript component:</p>
<pre><code class="language-tsx">import React, { useRef, useEffect } from "react";
import classNames from "classnames";

const HtmlDialog: React.FC = () =&gt; {
  const dialogRef = useRef&lt;HTMLDialogElement&gt;(null);

  useEffect(() =&gt; {
    const dialog = dialogRef.current;
    if (!dialog) return;

    const handleBackdropClick = (e: MouseEvent) =&gt; {
      const rect = dialog.getBoundingClientRect();
      if (
        e.clientX &lt; rect.left ||
        e.clientX &gt; rect.right ||
        e.clientY &lt; rect.top ||
        e.clientY &gt; rect.bottom
      ) {
        dialog.close();
      }
    };

    const handleClose = () =&gt; {
      console.log("dialog closed");
    };

    const handleCancel = (event: Event) =&gt; {
      console.log("dialog cancelled");
      event.preventDefault();
    };

    dialog.addEventListener("click", handleBackdropClick);
    dialog.addEventListener("close", handleClose);
    dialog.addEventListener("cancel", handleCancel);

    return () =&gt; {
      dialog.removeEventListener(
        "click",
        handleBackdropClick
      );
      dialog.removeEventListener("close", handleClose);
      dialog.removeEventListener("cancel", handleCancel);
    };
  }, []);

  const primaryBtn = classNames(
    "rounded-lg border border-sky-600 bg-sky-800",
    "px-5 py-2.5 text-sm font-medium text-sky-100",
    "hover:bg-sky-700 hover:text-white",
    "focus:z-10 focus:outline-none focus:ring-0"
  );

  const cancelBtn = classNames(
    "rounded-lg border border-slate-600 bg-slate-800",
    "px-5 py-2.5 text-sm font-medium text-slate-400",
    "hover:bg-slate-700 hover:text-white",
    "focus:z-10 focus:outline-none focus:ring-0"
  );

  const resetBtn = classNames(
    "rounded-lg border border-red-600 bg-red-800",
    "px-5 py-2.5 text-sm font-medium text-red-100",
    "hover:bg-red-700 hover:text-white",
    "focus:z-10 focus:outline-none focus:ring-0"
  );

  return (
    &lt;section
      className="flex flex-col items-center py-12"
    &gt;
      &lt;button
        type="button"
        className={primaryBtn}
        onClick={() =&gt; dialogRef.current?.showModal()}
      &gt;
        Open Dialog
      &lt;/button&gt;

      &lt;dialog
        ref={dialogRef}
        className={classNames(
          "inset-0 bg-zinc-50 bg-opacity-90",
          "backdrop:bg-slate-600 backdrop:bg-opacity-50",
          "open:animate-fade-in",
          "open:backdrop:animate-fade-in"
        )}
      &gt;
        &lt;div
          className="flex flex-col items-center gap-3 p-8"
        &gt;
          &lt;h1 className="text-4xl font-bold"&gt;Dialog&lt;/h1&gt;
          &lt;span&gt;You can see me&lt;/span&gt;
          &lt;form
            method="dialog"
            className="flex flex-col gap-3"
          &gt;
            &lt;input
              type="text"
              placeholder="Enter your name"
              className={classNames(
                "rounded-md border-2 border-gray-300",
                "px-3 py-2 focus:border-transparent",
                "focus:outline-none focus:ring-2",
                "focus:ring-indigo-400"
              )}
            /&gt;

            &lt;button type="submit" className={primaryBtn}&gt;
              Submit
            &lt;/button&gt;

            &lt;button
              formMethod="dialog"
              type="submit"
              className={cancelBtn}
            &gt;
              Cancel
            &lt;/button&gt;

            &lt;button
              type="reset"
              className={resetBtn}
              onClick={() =&gt; {
                dialogRef.current?.close();
                setTimeout(() =&gt; {
                  dialogRef.current?.showModal();
                }, 0);
              }}
            &gt;
              Reset
            &lt;/button&gt;
          &lt;/form&gt;
        &lt;/div&gt;
      &lt;/dialog&gt;
    &lt;/section&gt;
  );
};

export default HtmlDialog;
</code></pre>
<blockquote>
<p><strong>Tip</strong> : Notice how <code>event.preventDefault()</code> inside the <code>cancel</code> listener lets you intercept Escape-key dismissal when you need to confirm unsaved form changes before closing.</p>
</blockquote>
<hr />
<h3>Keep Exploring</h3>
<ul>
<li><a href="https://javascript.plainenglish.io/best-practices-for-using-typescript-with-react-bad13d851143">Best Practices for Using TypeScript with React</a></li>
<li><a href="https://medium.com/becoming-for-better/understanding-and-building-react-custom-hooks-a-practical-guide-037ad33d1cd1">Understanding and Building React Custom Hooks — A Practical Guide</a></li>
<li><a href="https://javascript.plainenglish.io/change-page-header-on-scroll-using-intersection-observer-api-a-dynamic-ux-approach-d09659a50e3d">Change Page Header on Scroll Using Intersection Observer API: A Dynamic UX Approach</a></li>
<li><a href="https://www.buymeacoffee.com/mkare/e/599267">React Custom Hooks TypeScript Pack &amp; Cheatsheets (Buy Me a Coffee)</a></li>
</ul>
<hr />
<p>Are you still reaching for third-party modal packages, or have you already switched to native <code>&lt;dialog&gt;</code> in production? I'd love to hear your experience 🧠💬</p>
<p><em>Written by Mustafa Morbel — software engineer and technical writer with over 17 years of experience building web applications with React, TypeScript, and modern frontend architectures.</em></p>
]]></content:encoded></item><item><title><![CDATA[Effectively Managing 404 Errors on the Server-Side in React SPAs with Nginx]]></title><description><![CDATA[Originally published on Medium (Medium). Read on Medium for free via Friend Link. ☕ Explore Developer Starter Kits & Guides illustration : Tisna Permadi…]]></description><link>https://mkare.hashnode.dev/effectively-managing-404-errors-on-the-server-side-in-react-spas-with-nginx</link><guid isPermaLink="true">https://mkare.hashnode.dev/effectively-managing-404-errors-on-the-server-side-in-react-spas-with-nginx</guid><category><![CDATA[react js]]></category><category><![CDATA[nginx]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 14:34:30 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium (Medium). <a href="https://medium.com/@mkare/effectively-managing-404-errors-on-the-server-side-in-spas-884ae11f528c?sk=f34b4aaa1d92d5192f6219d737af76c6">Read on Medium for free via Friend Link</a>.</em></p>
<p>☕ <strong><a href="https://www.buymeacoffee.com/mkare/extras">Explore Developer Starter Kits &amp; Guides</a></strong></p>
</blockquote>
<h3>Quick Takeaways</h3>
<ul>
<li><strong>Stop Masking 404s as 200 OK</strong> : Default SPA fallback rules return <code>index.html</code> with a <code>200 OK</code> status for missing URLs, blinding server monitoring and hurting SEO.</li>
<li><strong>Bridge React Router &amp; Nginx</strong> : Pair a catch-all client route that redirects to <code>/404</code> with an Nginx <code>error_page 404 /404</code> block so the server logs a true 404 while the SPA renders your not-found UI.</li>
<li><strong>Track Broken Routes in Logs</strong> : Use Nginx <code>access_log</code> and <code>error_log</code> to uncover dead links across React, Vue, or Angular deployments.</li>
</ul>
<hr />
<p><img src="https://cdn-images-1.medium.com/max/800/1*NIK8C_NrfgzOw7SWLNm3gA.png" alt="Diagram illustrating how a Single Page Application and Nginx coordinate to return real server-side 404 status codes" />
<em>illustration : Tisna Permadi</em></p>
<h3>Problem Definition</h3>
<p>When a user tries to directly access a specific address in an SPA, the server cannot find a matching HTML file for that path and would normally return a 404 error. However, most SPA setups are configured to handle this by returning the application's main <code>index.html</code> instead of a 404 page.</p>
<p>This keeps navigation smooth for the user, but it creates a blind spot for server-side monitoring and error-logging systems. The result? Your server reports a healthy <code>200 OK</code> response even though the route does not actually exist.</p>
<p>In this article, we will walk through how to effectively manage 404 errors on the server side in your SPAs, broken into four parts: SPA routing basics, React Router catch-all configuration, Nginx redirection, and server-side error tracking.</p>
<hr />
<h3>SPA and Routing: Basic Operation</h3>
<p>SPAs provide a seamless experience by dynamically loading all application content through a single HTML page. However, the server's unawareness of client-side routes can lead to silent 404 issues on direct URL access.</p>
<p>Left unhandled, this creates serious problems for server-side error logging, search engine indexing, and user experience. Understanding that gap between client-side routing and server-side responses is the first step toward fixing it.</p>
<hr />
<h3>React Router Configuration for 404 Error Handling</h3>
<p>React Router gives us a clean way to catch unknown paths in an SPA. Below is a complete example demonstrating how to configure a catch-all route that renders a dedicated <code>PageNotFound</code> component:</p>
<pre><code class="language-tsx">import React from "react";
import { Route, Link, Routes } from "react-router-dom";

export default function App() {
  return (
    &lt;div&gt;
      &lt;nav&gt;
        &lt;ul&gt;
          &lt;li&gt;
            &lt;Link to="/"&gt;Home&lt;/Link&gt;
          &lt;/li&gt;
          &lt;li&gt;
            &lt;Link to="/about"&gt;About&lt;/Link&gt;
          &lt;/li&gt;
          &lt;li&gt;
            {/* Link to catch-all route */}
            &lt;Link to="/does-not-exist"&gt;
              Catch all route
            &lt;/Link&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/nav&gt;

      &lt;Routes&gt;
        &lt;Route path="/about" element={&lt;About /&gt;} /&gt;
        &lt;Route path="/" element={&lt;Home /&gt;} /&gt;

        {/* Match when no other routes match */}
        &lt;Route path="*" element={&lt;PageNotFound /&gt;} /&gt;
      &lt;/Routes&gt;
    &lt;/div&gt;
  );
}

function Home() {
  return &lt;h2&gt;Home&lt;/h2&gt;;
}

function About() {
  return &lt;h2&gt;About&lt;/h2&gt;;
}

function PageNotFound() {
  return (
    &lt;div&gt;
      &lt;h2&gt;404 Page not found&lt;/h2&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>The <code>&lt;Route path="*"&gt;</code> component routes all undefined paths to <code>PageNotFound</code>. When a user enters an invalid URL, they see a clear 404 page inside the app.</p>
<p>However, that alone still leaves the server returning <code>200 OK</code>. To involve Nginx, using <code>window.location.href = "/404"</code> forces a full browser request so the server sees the <code>/404</code> path first. We can update the catch-all route as follows:</p>
<pre><code class="language-tsx">&lt;Route path="/404" element={&lt;PageNotFound /&gt;} /&gt;
&lt;Route
  path="*"
  element={() =&gt; {
    return &lt;&gt;{(window.location.href = "/404")}&lt;/&gt;;
  }}
/&gt;
</code></pre>
<p>Once the request hits <code>/404</code> on the Nginx side, the server can record a genuine 404 status while still serving the SPA bundle so React renders the <code>PageNotFound</code> view.</p>
<hr />
<h3>Nginx Configuration for SPA Redirection</h3>
<p>Nginx makes it straightforward to combine SPA fallback routing with proper server-side 404 handling. In the configuration below, normal routes fall back to <code>index.html</code>, while <code>/404</code> is handled explicitly via <code>error_page</code>:</p>
<pre><code class="language-nginx">server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    error_page 404 /404;

    location = /404 {
        internal;
        root   /usr/share/nginx/html;
        try_files /index.html;
    }
}
</code></pre>
<p>In this configuration, <code>try_files</code> tells Nginx to look for the requested URI first, and if no static file exists, to serve <code>index.html</code>. Marking <code>location = /404</code> as <code>internal</code> ensures it is only triggered through Nginx's internal error handling.</p>
<hr />
<h3>Application for Different Types of SPAs</h3>
<p>This same pattern applies to SPAs built with other JavaScript frameworks such as Vue and Angular. While each framework has its own client-side router syntax, the Nginx and container setup stays largely the same: route invalid paths to a dedicated <code>/404</code> endpoint so the server and browser stay in sync.</p>
<hr />
<h3>Server-Side Tracking of 404 Errors</h3>
<p>Once Nginx is aware of 404s, its built-in logging becomes far more useful. The <code>access_log</code> and <code>error_log</code> directives let you see exactly which missing URLs users and crawlers are hitting—giving you concrete data to fix broken links, tighten redirects, and protect your SEO strategy.</p>
<p>How does your team handle server-side 404s in production SPAs — Nginx rules, edge middleware, or SSR? I'd love to hear your thoughts 🧠💬</p>
<hr />
<h3>Keep Exploring</h3>
<p>If you found this guide helpful, check out these related React and TypeScript resources:</p>
<ul>
<li><strong><a href="https://javascript.plainenglish.io/best-practices-for-using-typescript-with-react-bad13d851143">Best Practices for Using TypeScript with React</a></strong></li>
<li><strong><a href="https://medium.com/becoming-for-better/understanding-and-building-react-custom-hooks-a-practical-guide-037ad33d1cd1">Understanding and Building React Custom Hooks — A Practical Guide</a></strong></li>
<li><strong><a href="https://javascript.plainenglish.io/html-native-dialog-component-in-react-with-tailwind-css-2b23356ef036">HTML Native Dialog Component in React with Tailwind CSS</a></strong></li>
<li><strong><a href="https://www.buymeacoffee.com/mkare/e/599267">React Custom Hooks TypeScript Pack &amp; Toolkits (Buy Me a Coffee)</a></strong></li>
</ul>
<hr />
<h3>About the Author</h3>
<p>I'm <strong>Mustafa Morbel</strong> — Senior Frontend Engineer with over 17 years of experience building scalable React architectures, WebGL applications, and resilient web systems.</p>
]]></content:encoded></item><item><title><![CDATA[Change Page Header on Scroll Using the Intersection Observer API]]></title><description><![CDATA[Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link. ☕ Explore Developer Starter Kits & Guides Using the…]]></description><link>https://mkare.hashnode.dev/change-page-header-on-scroll-using-the-intersection-observer-api</link><guid isPermaLink="true">https://mkare.hashnode.dev/change-page-header-on-scroll-using-the-intersection-observer-api</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[CSS]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 14:31:54 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium (JavaScript in Plain English). <a href="https://javascript.plainenglish.io/change-page-header-on-scroll-using-intersection-observer-api-a-dynamic-ux-approach-d09659a50e3d?sk=22f3338479cbeab39b69de180f26532e">Read on Medium for free via Friend Link</a>.</em></p>
<p>☕ <strong><a href="https://www.buymeacoffee.com/mkare/extras">Explore Developer Starter Kits &amp; Guides</a></strong></p>
</blockquote>
<h3>Quick Takeaways</h3>
<ul>
<li><strong>Zero scroll-listener overhead:</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">Intersection Observer</a> fires asynchronously only when visibility crosses a threshold—no <code>window.onscroll</code> throttling needed.</li>
<li><strong>One-line class toggle:</strong> Observing a lightweight sentinel <code>&lt;div&gt;</code> above your content lets <code>header.classList.toggle("active", !entry.isIntersecting)</code> drive the sticky transition.</li>
<li><strong>Pure CSS offset control:</strong> Adjusting <code>top</code> on <code>[data-observer-intercept]</code> delays the header transition until the user scrolls past an exact pixel threshold.</li>
</ul>
<hr />
<p><img src="https://cdn-images-1.medium.com/max/800/1*H4sOuyKTvt0Hq6Fc_ucpSQ.jpeg" alt="Sticky page header changing background and shadow on scroll using the JavaScript Intersection Observer API" />
<em>Using the Intersection Observer API to toggle a sticky header's active styles as the page scrolls.</em></p>
<h3>Why Intersection Observer Beats Scroll Listeners</h3>
<p>The Intersection Observer API helps us determine whether an element is currently visible within the user's viewport or has scrolled out of view. Instead of firing on every pixel of scroll, it notifies your callback only when visibility changes. By utilizing this API, we can create a header that dynamically adjusts its appearance as the user scrolls through the page.</p>
<p>Let's start with a minimal example that watches a single box element as it enters and leaves the viewport:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;style&gt;
    .box {
      width: 200px;
      height: 200px;
      background-color: red;
      margin: 1000px auto;
    }

    .box.active {
      background-color: green;
    }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;div class="box"&gt;&lt;/div&gt;

  &lt;script&gt;
    const observer = new IntersectionObserver((entries) =&gt; {
      entries.forEach((entry) =&gt; {
        if (entry.isIntersecting) {
          // Box is visible: add the "active" class
          entry.target.classList.add("active");
        } else {
          // Box is hidden: remove the "active" class
          entry.target.classList.remove("active");
        }
      });
    });

    const box = document.querySelector(".box");
    observer.observe(box);
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>In this example, we create a box element and use the Intersection Observer to track its visibility. Initially, the box is off-screen. However, when the box becomes visible, we add the <code>active</code> class to it, giving it a green background color. When the box scrolls out of view again, we remove the <code>active</code> class, and it returns to red.</p>
<p>The Intersection Observer watches whether the box is visible within the page and reacts accordingly. That same pattern is all we need to build a scroll-aware sticky header.</p>
<hr />
<p><img src="https://cdn-images-1.medium.com/max/800/1*m7_kUaNYY9fc-sIi2hukCA.png" alt="Diagram showing an invisible intercept sentinel div triggering a fixed sticky header class change on scroll" />
<em>Observing a lightweight sentinel element above the main content lets the header react to scroll without a scroll listener.</em></p>
<h3>Change Page Header on Scroll</h3>
<p>Here is the complete, self-contained HTML implementation for a sticky header that transitions its background, text color, and drop shadow once the user scrolls past the top of the page:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;style&gt;
      header {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        background-color: #f5f6fa;
        padding: 10px;
        z-index: 999;
      }

      /* Avoid content overlap under the fixed header */
      body {
        margin-top: 50px;
      }

      /* Extra height to enable page scrolling */
      .content {
        height: 2000px;
      }

      header.active {
        background-color: #273c75;
        box-shadow: hsla(0 0% 0% / 0.1) 0 0.5rem 1rem;
        color: #f5f6fa;
        transition-duration: 400ms;
      }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;header id="header"&gt;
      &lt;h1&gt;Sticky Header&lt;/h1&gt;
    &lt;/header&gt;

    &lt;div class="content"&gt;
      &lt;!-- Your page content goes here --&gt;
    &lt;/div&gt;

    &lt;script&gt;
      const header = document.getElementById("header");
      const intercept = document.createElement("div");
      const content = document.querySelector(".content");

      intercept.setAttribute("data-observer-intercept", "");
      content.before(intercept);

      const observer = new IntersectionObserver(([entry]) =&gt; {
        const scrolledPast = !entry.isIntersecting;
        header.classList.toggle("active", scrolledPast);
      });

      observer.observe(intercept);
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>The callback function of the Intersection Observer extracts the first <code>entry</code> from the array of entries using <code>([entry])</code>. It then uses <code>classList.toggle</code> to add the <code>active</code> class to the header when <code>entry.isIntersecting</code> is <code>false</code> (meaning the sentinel has scrolled out of the viewport) and remove it when <code>entry.isIntersecting</code> is <code>true</code>.</p>
<blockquote>
<p><strong>Tip:</strong> Save the code in an HTML file and open it in a web browser to see the sticky header transition into its active state as you scroll. Feel free to adjust the colors, shadow, and transition duration to match your design system.</p>
</blockquote>
<hr />
<h3>How the Intercept Sentinel Works Step by Step</h3>
<p>First, grab the header, create a lightweight intercept element, and select the main content container:</p>
<pre><code class="language-js">const header = document.getElementById("header");
const intercept = document.createElement("div");
const content = document.querySelector(".content");
</code></pre>
<p>Next, tag the intercept element with a data attribute so we can target it cleanly in CSS:</p>
<pre><code class="language-js">intercept.setAttribute("data-observer-intercept", "");
</code></pre>
<p>Insert the intercept element directly before the content container:</p>
<pre><code class="language-js">content.before(intercept);
</code></pre>
<p>Create an Intersection Observer and start watching the intercept element:</p>
<pre><code class="language-js">const observer = new IntersectionObserver(([entry]) =&gt; {
  const scrolledPast = !entry.isIntersecting;
  header.classList.toggle("active", scrolledPast);
});

observer.observe(intercept);
</code></pre>
<p>With the intercept <code>&lt;div&gt;</code> in place, we have a dedicated sentinel point on the page to observe. Whenever that sentinel enters or leaves the viewport, the Intersection Observer fires and toggles the header's <code>active</code> class.</p>
<p>When inspecting the DOM using the browser's developer tools, you will see the following structure:</p>
<pre><code class="language-html">&lt;div data-observer-intercept&gt;&lt;/div&gt;
&lt;header id="header"&gt;
  &lt;!-- Header content goes here --&gt;
&lt;/header&gt;
</code></pre>
<p>Additionally, you can control <em>when</em> the header transitions by positioning the intercept element with CSS:</p>
<pre><code class="language-css">[data-observer-intercept] {
  position: absolute;
  top: 200px;
}
</code></pre>
<p>When scrolling the page, the header shadow and active background won't appear immediately. Instead, the transition waits until the page has scrolled past the 200-pixel offset.</p>
<hr />
<h3>Keep Exploring</h3>
<ul>
<li><a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8">Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes</a></li>
<li><a href="https://javascript.plainenglish.io/html-native-dialog-component-in-react-with-tailwind-css-2b23356ef036">HTML Native Dialog Component in React with Tailwind CSS</a></li>
<li><a href="https://javascript.plainenglish.io/best-practices-for-using-typescript-with-react-bad13d851143">Best Practices for Using TypeScript with React</a></li>
<li><a href="https://www.buymeacoffee.com/mkare">Toolkit &amp; Starter Kits on Buy Me a Coffee</a></li>
</ul>
<p>How are you handling sticky headers and scroll-triggered UI transitions in your projects? I'd love to hear your approach 🧠💬</p>
<hr />
<h3>👋 About the Author</h3>
<p><strong>Mustafa Morbel</strong> is a senior software engineer and engineering leader with over 17 years of experience building web applications, frontend architectures, and developer tools.</p>
]]></content:encoded></item><item><title><![CDATA[Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript]]></title><description><![CDATA[Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link. 🎮 Try the Live Interactive Demo · 📦 GitHub Repo &…]]></description><link>https://mkare.hashnode.dev/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript</link><guid isPermaLink="true">https://mkare.hashnode.dev/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[GameDev]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 14:13:30 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium (JavaScript in Plain English).</em> <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11?source=friends_link&amp;sk=ff5390a11e2d97b29e82dc41a6572272"><em>Read on Medium for free via Friend Link</em></a><em>.</em></p>
<p>🎮 <a href="https://m2-md.github.io/fixed-timestep-render-interpolation/"><strong>Try the Live Interactive Demo</strong></a> · 📦 <a href="https://github.com/m2-md/fixed-timestep-render-interpolation"><strong>GitHub Repo &amp; Vitest Suite</strong></a> · ⚡ <a href="https://www.buymeacoffee.com/mkare/e/599265"><strong>Get the TS 2D Canvas Physics Starter Kit</strong></a></p>
</blockquote>
<img src="https://raw.githubusercontent.com/m2-md/fixed-timestep-render-interpolation/main/assets/demo.gif" alt="Interactive Demo Preview" style="display:block;margin:0 auto" />

<img src="https://miro.medium.com/v2/resize:fit:1400/1*qGEXMRosGad2hVIA9CRpzg.png" alt="Architecture diagram of a TypeScript fixed-timestep 60Hz physics metronome decoupled from 144Hz Canvas render interpolation" style="display:block;margin:0 auto" />

<p><em>A 60Hz fixed-timestep accumulator drives deterministic physics while alpha interpolation keeps 144Hz rendering smooth.</em></p>
<h3>Quick Takeaways</h3>
<ul>
<li><strong>Accumulator Loop:</strong> Advance physics in invariant <code>STEP = 1 / 60</code> slices so trajectories match bit-for-bit at any FPS.</li>
<li><strong>Spiral-of-Death Guard:</strong> Clamp spikes (<code>MAX_FRAME</code>) and cap sub-steps (<code>MAX_STEPS</code>) so slow frames never freeze the tab.</li>
<li><strong>Alpha Render Interpolation:</strong> Blend <code>lerp(prev, pos, alpha)</code> using remainder <code>acc / STEP</code> for silky 144Hz visuals.</li>
</ul>
<hr />
<p>Last week, I launched the exact same game on two different computers. My desktop has a 144 Hz gaming monitor; my aging laptop struggles to hit 40 FPS on a good day. I launched the ball from the exact same coordinates at the exact same angle.</p>
<p>On the two machines, the ball landed in two completely different places.</p>
<p>In game development, this is a nightmare.</p>
<p>A physics simulation should never depend on the screen's refresh rate. Whether a player sees 60 FPS, 30 FPS, or 144 FPS must not dictate where a projectile lands. Yet that was precisely what our physics engine was doing. At the core of that custom-built engine from <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">our previous article</a>, the heartbeat was this loop:</p>
<pre><code class="language-ts">// Reminder from canvas-physics-from-scratch — OLD, variable-dt loop.
// Counter-example only; not in this project's repo.
const dt = Math.min((now - last) / 1000, 1 / 30); // delta time between frames
last = now;

world.step(dt); // advance physics by elapsed time
draw();
</code></pre>
<p>In that project, we capped <code>dt</code> (delta time, the elapsed seconds between frames) with <code>Math.min</code> so that switching browser tabs wouldn't cause the ball to teleport through walls upon return. It was a small band-aid. In this article, we peel off that band-aid and heal the underlying wound: we make physics <strong>fixed-timestep</strong> and completely decouple rendering from it. By the end, we'll have a loop that behaves identically down to the bit on every single machine, yet still paints effortlessly at 144 frames per second.</p>
<p>The mental model for this entire piece is a <strong>metronome</strong> — because the whole design revolves around a single core idea. A variable-dt physics loop behaves like an emotional drummer: when excited (a fast machine), they speed up; when exhausted (a sluggish machine), they drag behind. The same song sounds completely different every time. We are going to put a metronome in front of this drummer. The metronome clicks exactly 60 times every second — regardless of the hardware. The renderer, meanwhile, behaves like an independent dancer flowing at their own tempo. The entire craft lies in separating the two, and then connecting them with mathematical elegance.</p>
<p>Our roadmap covers five key steps: dissecting the nonlinear math of variable delta time, building an accumulator loop, neutralizing the catastrophic "spiral of death," synthesizing in-between frames with render interpolation, and proving bit-for-bit determinism with automated Vitest suites.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*j_7EIqCveu9W_JPLwvPVeA.png" alt="Comparison diagram showing projectile trajectory divergence under variable delta-time semi-implicit Euler integration" style="display:block;margin:0 auto" />

<p><em>Variable delta time causes semi-implicit Euler trajectories to drift across different display refresh rates.</em></p>
<h3>The Variable-dt Trap</h3>
<p>First, let's look closely at the problem. "It plays differently on every machine" might sound like a vague observation, but beneath it lies hard, unforgiving mathematics.</p>
<p>Our physics engine uses <strong>semi-implicit Euler</strong> (symplectic Euler) integration. It takes just two lines:</p>
<pre><code class="language-ts">b.vel = add(b.vel, scale(this.gravity, dt)); // velocity += gravity * dt
b.pos = add(b.pos, scale(b.vel, dt));        // position += (new) velocity * dt
</code></pre>
<p>The subtle trap lives in the second line: the position update uses the <em>newly computed</em> velocity for that frame. This gives the integrator its beloved numerical stability — but it also makes position updates <strong>nonlinear with respect to</strong> <code>dt</code>. If you take a time interval <code>dt</code> and split it into two sub-steps of <code>dt / 2</code>, you get a different mathematical result than taking a single step of <code>dt</code>.</p>
<p>Let's do the algebra by hand.</p>
<p>Taking a single step of duration <code>dt</code>:</p>
<pre><code class="language-text">v₁ = v₀ + g · dt
x₁ = x₀ + v₁ · dt = x₀ + v₀ · dt + g · dt²
</code></pre>
<p>Now let's divide the exact same elapsed time into two steps of <code>dt / 2</code>.</p>
<p>First half-step:</p>
<pre><code class="language-text">v½ = v₀ + g · (dt / 2)
x½ = x₀ + v½ · (dt / 2) = x₀ + v₀ · (dt / 2) + g · (dt² / 4)
</code></pre>
<p>Second half-step:</p>
<pre><code class="language-text">v₁ = v½ + g · (dt / 2) = v₀ + g · dt
x₂ = x½ + v₁ · (dt / 2) = x₀ + v₀ · dt + (3/4) · g · dt²
</code></pre>
<p>Compare the position results: <code>g · dt²</code> versus <code>(3/4) · g · dt²</code>.</p>
<p>The exact same physical duration yields two different spatial positions. Purely because we chopped up time differently.</p>
<p>That is why my 144 Hz monitor and my 40 FPS laptop diverged. The fast machine took many tiny <code>dt</code> steps; the slow machine took fewer, larger <code>dt</code> steps. Even with the same total elapsed time, the trajectories drifted apart.</p>
<p>To make matters worse, think about what <code>Math.min(dt, 1 / 30)</code> does on a slow machine: if a frame takes 40 ms, we tell physics that only 33.3 ms passed. 6.7 milliseconds simply evaporate into thin air. The physics simulation literally falls behind real time.</p>
<p>And then there is <strong>tunneling</strong>. When <code>dt</code> grows large, <code>position += velocity * dt</code> causes objects to leap across vast distances in a single frame. A fast-moving projectile can jump clean from one side of a thin barrier to the other without ever touching it — completely bypassing collision detection. On low-FPS hardware, tunneling is rampant. Our old band-aid (<code>Math.min</code>) existed solely to keep those jumps small. It didn't solve the problem; it merely swept it under the rug.</p>
<p>So, how do we build the metronome?</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*3hNzcMUfyTDdrSXHvdVVsQ.png" alt="Timeline diagram converting irregular browser frame intervals into uniform 16.67ms fixed-timestep accumulator physics ticks" style="display:block;margin:0 auto" />

<p><em>The accumulator stores irregular wall-clock frame durations and spends them in uniform 16.67ms (60Hz) physics steps.</em></p>
<h3>Setting the Metronome: The Fixed-Timestep Accumulator</h3>
<p>The concept is surprisingly simple. We will never tell the physics engine: <em>"advance by however much real time just elapsed."</em> Instead, we advance it by an invariant, fixed slice of time: <code>STEP = 1 / 60</code> seconds. That is the metronome's tick interval.</p>
<pre><code class="language-text">Real Time (irregular): |-- 16ms --|--- 22ms ---|- 14ms -|
Metronome (fixed):     |- 16.6ms -|- 16.6ms -|- 16.6ms -|
</code></pre>
<p>But real-world wall-clock time is anything but fixed. One frame takes 16.6 ms, another 22 ms, then the user switches tabs and 400 ms elapses. How do we convert this irregular real time into deterministic, uniform ticks?</p>
<p>With a piggy bank. In game architecture, this pattern is called an <strong>accumulator</strong>.</p>
<p>On every frame, we deposit the elapsed real time into the accumulator. If at least one full <code>STEP</code> has accumulated, we spend one tick. If two <code>STEP</code>s have accumulated, we spend two ticks. If there is less than <code>STEP</code> remaining in the accumulator, we don't spend it — we carry that fractional remainder over to the next frame.</p>
<pre><code class="language-ts">// Step 1: Naive accumulator — no spiral-of-death protection, no snapshots yet.
// Pedagogical stepping stone: final implementation is in src/sim.ts + src/demo.ts.
const STEP = 1 / 60; // Metronome tick interval — physics advances 60 times a second
let acc = 0;         // Accumulator: unspent wall-clock time
let last = performance.now();

function frame(now: number) {
  const frameTime = (now - last) / 1000; // seconds elapsed this frame
  last = now;

  acc += frameTime; // deposit real time into the accumulator

  while (acc &gt;= STEP) {
    world.step(STEP); // every tick consumes the EXACT same slice of time
    acc -= STEP;
  }

  draw();
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</code></pre>
<p>Notice the critical difference: <code>world.step</code> no longer receives <code>frameTime</code>. It <em>always</em> receives <code>STEP</code>. Physics cares how many times it gets called, but every invocation executes with the identical time step. A fast machine might run one tick per frame, while a struggling machine runs three — but every individual tick executes the exact same <code>step(STEP)</code> equation. A 10-second simulation runs exactly 600 ticks on both machines. Same sequence, same time step, identical outcome.</p>
<p>The <code>dt / 2</code> divergence from the previous section completely vanishes: there is no <code>dt / 2</code> anymore. There is only <code>STEP</code>, always <code>STEP</code>.</p>
<p><code>requestAnimationFrame</code> simply hooks into the display refresh cycle: the browser calls <code>frame</code> right before painting, passing high-resolution timestamp <code>now</code>. The browser counts real time for us; our sole job is to slice it into uniform chunks.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*gt8gq47pePfGSVAJjek2aQ.png" alt="Flowchart illustrating the game loop spiral of death and how MAX_FRAME clamping plus a MAX_STEPS ceiling prevent freezes" style="display:block;margin:0 auto" />

<p><em>Clamping frame spikes with MAX_FRAME and capping sub-steps with MAX_STEPS prevents runaway CPU catch-up loops.</em></p>
<h3>The Spiral of Death and Breaking the Loop</h3>
<p>Take a hard look at the <code>while</code> loop above. There is a hidden landmine inside it.</p>
<p>What happens if a frame takes an unusually long time? Suppose the user minimizes the tab, the laptop goes to sleep, or the garbage collector pauses execution. Suddenly, <code>frameTime</code> arrives at 3.0 seconds.</p>
<p>We deposit 3 seconds into the accumulator. To empty it, the <code>while</code> loop must execute 180 physics ticks in a single frame. But running 180 physics steps takes time — say, 50 ms. While those 50 ms are running, more wall-clock time elapses, filling the accumulator further before the frame can even finish. The loop can never catch up. The browser hangs, the CPU pegs at 100%, and the laptop fans spin up like a jet engine.</p>
<p>In game engineering, this is known as the <strong>spiral of death</strong>: the metronome demands more ticks than your CPU can afford to pay. As you scramble to catch up, the debt grows; as the debt grows, catching up becomes even more impossible. A classic infinite downward spiral.</p>
<p>The solution has two layers:</p>
<ol>
<li><strong>Clamp catastrophic frame spikes</strong> at the source. This is the legitimate, rightful place for our <code>Math.min</code> reflex.</li>
<li><strong>Impose a tick ceiling</strong> per frame. If we hit the ceiling, we make an executive decision: we <strong>forgive the unpayable debt</strong>.</li>
</ol>
<pre><code class="language-ts">// Step 2: Frame clamping + tick ceiling added (snapshots still to come).
// Full implementation in src/demo.ts (STEP is a `let` there to support runtime slider changes).
const STEP = 1 / 60;
const MAX_STEPS = 5;    // At most 5 physics ticks per frame
const MAX_FRAME = 0.25; // Clamp any single frame to 250ms

let acc = 0;
let last = performance.now();

function frame(now: number) {
  let frameTime = (now - last) / 1000;
  last = now;

  if (frameTime &gt; MAX_FRAME) frameTime = MAX_FRAME; // 1) Clamp giant spikes
  acc += frameTime;

  let steps = 0;
  while (acc &gt;= STEP &amp;&amp; steps &lt; MAX_STEPS) {         // 2) Impose tick ceiling
    world.step(STEP);
    acc -= STEP;
    steps++;
  }

  if (steps === MAX_STEPS) acc = 0; // 3) Hit the ceiling: drop debt to break the death spiral

  draw();
  requestAnimationFrame(frame);
}
</code></pre>
<p>The line <code>if (steps === MAX_STEPS) acc = 0;</code> is deliberate surrender. It says: <em>"This machine cannot keep up with real time right now. Instead of burning down the CPU trying to catch up, let's discard the lost time."</em></p>
<p>The result? On extreme frame drops or heavy tab switches, the game temporarily slows down (slow motion) instead of freezing solid. Among bad options, it is by far the best engineering compromise.</p>
<p>Tuning these numbers depends on your game's workload. <code>MAX_STEPS = 5</code> at 60 Hz provides an 83 ms catch-up budget per frame — plenty for most web games. For heavy simulations, you might tune it to 3; for lightweight loops, 10. There is no magic number; you profile and decide.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*pp-tw3atBooQXocN2fTWqw.png" alt="Diagram showing temporal aliasing jitter when 144Hz display rendering reads uninterpolated 60Hz discrete physics positions" style="display:block;margin:0 auto" />

<p><em>Drawing discrete 60Hz physics ticks directly on a 144Hz monitor produces draw-draw-jump temporal aliasing.</em></p>
<h3>Decoupling Update from Render</h3>
<p>So far, our metronome ticks reliably. But run this code on screen, and an ugly visual problem immediately jumps out at you.</p>
<p>Physics updates 60 times a second. If you have a 144 Hz display, you are drawing 144 frames per second — but physics isn't updating that frequently. On many frames, the <code>while</code> loop doesn't tick at all (the accumulator hasn't gathered a full <code>STEP</code> yet).</p>
<p>On that frame, you draw the ball at the exact same position as the previous frame. Then on the next frame, it's still in the same place. Then suddenly a tick executes, and the ball jumps. Draw-draw-<strong>jump</strong>, draw-draw-<strong>jump</strong>.</p>
<p>This visual artifact is called <strong>temporal aliasing</strong>, and your eyes register it as irritating <strong>micro-stutter</strong> (visual jitter). Here is the cruel irony: our physics is now completely deterministic and mathematically correct, yet the animation looks noticeably choppier. Because rendering is trapped by the discrete ticks of the physics engine.</p>
<p>The breakthrough insight: <strong>Update runs at a fixed rate; Render runs at the display's refresh rate — and Render interpolates the gap between physics ticks.</strong></p>
<p>Physics marches to the metronome; the renderer dances at screen refresh rate. Our job is to synthesize the dancer's in-between poses.</p>
<p>To do that, all we need is the leftover remainder in the accumulator. When the <code>while</code> loop finishes, <code>acc</code> contains a fraction of time strictly less than <code>STEP</code> — representing how close we are to the <em>next</em> tick. We normalize this into a 0 to 1 progress ratio:</p>
<pre><code class="language-ts">const alpha = acc / STEP; // Between 0 and 1: progress between the last tick and the next tick
</code></pre>
<p><code>alpha = 0</code> means <em>"we are sitting exactly on the last tick."</em> <code>alpha = 0.5</code> means <em>"we are halfway between two ticks."</em> This single scalar is the key to silky-smooth rendering.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*HLGy2VR6A60mmfaf-IdWkA.png" alt="Vector diagram of linear render interpolation blending previous and current physics snapshots using alpha remainder ratio" style="display:block;margin:0 auto" />

<p><em>Linear interpolation blends prev and pos by alpha = acc / STEP, trading one tick of latency for liquid-smooth motion.</em></p>
<h3>Render Interpolation: Drawing Between the Ticks</h3>
<p>Now that we have <code>alpha</code>, we need one more ingredient: each body must retain both its <strong>current</strong> position (<code>pos</code>) and its position at the <strong>previous tick</strong> (<code>prev</code>). By interpolating between <code>prev</code> and <code>pos</code> by factor <code>alpha</code>, we draw the body exactly where it should appear at that sub-frame instant.</p>
<pre><code class="language-text">Previous (prev) ---- Render (alpha) ---- Current (pos)
  [ t = 0.0 ]         [ t = 0.65 ]        [ t = 1.0 ]
</code></pre>
<p>This requires a tiny addition to our physics engine: right before every tick, copy the current position into <code>prev</code>.</p>
<pre><code class="language-ts">// src/world.ts — also includes a createBody helper (where prev initializes to pos)
export interface Body {
  pos: Vec2; // current (curr) position
  prev: Vec2; // position at previous tick — used for interpolation
  vel: Vec2;
  radius: number;
  bounciness: number;
}

export class World {
  bodies: Body[] = [];
  gravity: Vec2;

  constructor(public width: number, public height: number, gravityY = 900) {
    this.gravity = vec(0, gravityY);
  }

  add(b: Body): Body {
    this.bodies.push(b);
    return b;
  }

  // Called BEFORE stepping: prev = curr. The "past" endpoint of interpolation.
  snapshot() {
    for (const b of this.bodies) {
      b.prev.x = b.pos.x;
      b.prev.y = b.pos.y;
    }
  }

  // Single FIXED step — dt is identical (STEP) on every call.
  step(dt: number) {
    for (const b of this.bodies) {
      b.vel = add(b.vel, scale(this.gravity, dt)); // semi-implicit Euler
      b.pos = add(b.pos, scale(b.vel, dt));
      this.collideWalls(b);
    }
  }

  private collideWalls(b: Body) {
    if (b.pos.x - b.radius &lt; 0) {
      b.pos.x = b.radius;
      b.vel.x = -b.vel.x * b.bounciness;
    }
    if (b.pos.x + b.radius &gt; this.width) {
      b.pos.x = this.width - b.radius;
      b.vel.x = -b.vel.x * b.bounciness;
    }
    if (b.pos.y - b.radius &lt; 0) {
      b.pos.y = b.radius;
      b.vel.y = -b.vel.y * b.bounciness;
    }
    if (b.pos.y + b.radius &gt; this.height) {
      b.pos.y = this.height - b.radius;
      b.vel.y = -b.vel.y * b.bounciness;
    }
  }
}
</code></pre>
<p>Notice how <code>step</code> remains virtually untouched from our original physics engine. All we added was the <code>snapshot()</code> method and the <code>prev</code> field. We didn't alter the math of the engine; we merely gave it a memory buffer to assist the renderer.</p>
<p>Now we complete the loop with <code>snapshot()</code>. Right before each step, we update <code>prev</code>:</p>
<pre><code class="language-ts">// src/demo.ts — final tick loop inside frame()
while (acc &gt;= STEP &amp;&amp; steps &lt; MAX_STEPS) {
  world.snapshot();      // prev = curr (BEFORE stepping)
  world.step(STEP);      // advance physics by fixed STEP
  acc -= STEP;
  steps++;
}
</code></pre>
<p>When the <code>while</code> loop finishes, <code>prev</code> holds the position at the start of the final tick, and <code>pos</code> holds the position at the end of that tick. <code>alpha</code> tells us exactly where we stand between them.</p>
<p>All that remains is drawing: instead of drawing at <code>pos</code>, we interpolate between <code>prev</code> and <code>pos</code> by <code>alpha</code>.</p>
<p>We add a linear interpolation helper (<code>lerp</code>) to our vector math:</p>
<pre><code class="language-ts">// Linear interpolation between two points by ratio t (0..1)
export const lerp = (a: Vec2, b: Vec2, t: number): Vec2 =&gt;
  vec(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
</code></pre>
<p>And update our rendering routine:</p>
<pre><code class="language-ts">// src/demo.ts — core render logic
function render(alpha: number) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (const b of world.bodies) {
    // OFF: direct pos -&gt; ball is locked to discrete physics ticks, producing visual jitter
    // ON:  interpolates between prev and pos by alpha -&gt; buttery-smooth display
    const p = interpolate ? lerp(b.prev, b.pos, alpha) : b.pos;

    ctx.beginPath();
    ctx.arc(p.x, p.y, b.radius, 0, Math.PI * 2);
    ctx.fill();
  }
}
</code></pre>
<p>Let me share a hesitation I had when first implementing this, because it initially confused me. Interpolation does not predict the future — it renders the past. Because we are blending between <code>prev</code> and <code>pos</code>, the ball drawn on screen is actually <strong>one physics tick behind</strong> real-time simulation state (≈16 ms at 60 Hz).</p>
<p>That might sound like a penalty, but 16 ms is imperceptible to human eyes, and in return, you get liquid-smooth motion. The alternative is <strong>extrapolation</strong> (predicting ahead into the future). But extrapolation during high-speed collisions is notoriously jarring: the renderer predicts the ball passing through a wall, and then snaps it backward when the collision solver resolves on the next tick. That visual popping is far worse. Almost every commercial game engine chooses interpolation. I do too.</p>
<p>To truly <em>see</em> this difference, open the <a href="https://m2-md.github.io/fixed-timestep-render-interpolation/">interactive demo</a>. It features a "Physics Hz" slider: intentionally drag physics down to 4 ticks per second.</p>
<p>With interpolation turned OFF, the ball teleports 4 times a second — choppy, jagged, and broken.</p>
<p>Toggle interpolation ON, and that exact same 4-tick physics suddenly glides across the screen at 60 FPS. The physics calculation underneath is 100% identical; the only difference is what your eyes perceive.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*B9nlYCRdqo0xA-GDXLFKYg.png" alt="End-to-end HTML5 Canvas game loop pipeline connecting requestAnimationFrame, fixed accumulator steps, and lerp rendering" style="display:block;margin:0 auto" />

<p><em>The complete HTML5 Canvas loop: clamp frameTime, snapshot and step fixed ticks, then render at interpolated coordinates.</em></p>
<h3>Wiring It Together on Canvas</h3>
<p>Let's combine all the moving parts into a single runnable loop. This is the heart of the demo — a bouncing ball, plus controls to "simulate low FPS" and "toggle interpolation":</p>
<pre><code class="language-ts">import { vec, lerp } from "./vec";
import { World, createBody } from "./world";

const canvas = document.querySelector&lt;HTMLCanvasElement&gt;("#game")!;
const ctx = canvas.getContext("2d")!;

const world = new World(canvas.width, canvas.height, 900);
const ball = world.add(createBody(120, 80, 24, 0.85));
ball.vel = vec(220, 0); // initial sideways velocity

let STEP = 1 / 60; // "Physics Hz" slider changes this at runtime
const MAX_STEPS = 5;
const MAX_FRAME = 0.25;

let interpolate = true; // toggled by button
let slowMotion = false; // "simulate low FPS" — intentionally slows down frames
let acc = 0;
let last = performance.now();

function frame(now: number) {
  let frameTime = (now - last) / 1000;
  last = now;
  if (frameTime &gt; MAX_FRAME) frameTime = MAX_FRAME;

  // To simulate low FPS, we use wall-clock time as is;
  // when slowMotion is active, we intentionally delay rendering to produce large frameTime.
  acc += frameTime;

  let steps = 0;
  while (acc &gt;= STEP &amp;&amp; steps &lt; MAX_STEPS) {
    world.snapshot();
    world.step(STEP);
    acc -= STEP;
    steps++;
  }
  if (steps === MAX_STEPS) acc = 0;

  const alpha = acc / STEP;
  render(alpha);
  updateHud(frameTime, steps);

  if (slowMotion) {
    // Simulate a heavy / long frame: delay the next frame
    setTimeout(() =&gt; requestAnimationFrame(frame), 90);
  } else {
    requestAnimationFrame(frame);
  }
}

function render(alpha: number) {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (const b of world.bodies) {
    const p = interpolate ? lerp(b.prev, b.pos, alpha) : b.pos;
    ctx.beginPath();
    ctx.arc(p.x, p.y, b.radius, 0, Math.PI * 2);
    ctx.fillStyle = "#e91e63";
    ctx.fill();
  }
}
</code></pre>
<p>Now we bind the three interactive controls from <code>index.html</code>: the interpolation checkbox, the low-FPS simulator, and the "Physics Hz" slider. The slider mutates <code>STEP</code> dynamically at runtime — providing visual proof of our architectural thesis. We also hook up a lightweight HUD counter:</p>
<pre><code class="language-ts">// --- Controls: the three inputs in index.html drive the live demo ---
const interpEl = document.querySelector&lt;HTMLInputElement&gt;("#interp")!;
const slowEl = document.querySelector&lt;HTMLInputElement&gt;("#slow")!;
const hzEl = document.querySelector&lt;HTMLInputElement&gt;("#hz")!;
const hzOut = document.querySelector&lt;HTMLSpanElement&gt;("#hzval")!;
const hud = document.querySelector&lt;HTMLSpanElement&gt;("#hud")!;

interpEl.addEventListener("change", () =&gt; (interpolate = interpEl.checked));
slowEl.addEventListener("change", () =&gt; (slowMotion = slowEl.checked));
hzEl.addEventListener("input", () =&gt; {
  const hz = Number(hzEl.value);
  STEP = 1 / hz; // readjust metronome tick interval
  hzOut.textContent = String(hz);
});

let fps = 0;
function updateHud(frameTime: number, steps: number) {
  // Smooth FPS with a simple exponential moving average
  fps += (1 / Math.max(frameTime, 1e-3) - fps) * 0.1;
  hud.textContent = `${fps.toFixed(0)} FPS • ${steps} ticks/frame`;
}

requestAnimationFrame(frame);
</code></pre>
<p>The <code>slowMotion</code> trick is simple yet remarkably effective: <code>setTimeout(..., 90)</code> delays the next frame intentionally. <code>frameTime</code> inflates, forcing the accumulator to discharge multiple physics ticks per frame. This accurately replicates what happens on a struggling device. In this mode, turning interpolation OFF makes jitter blatantly obvious; turning it ON shows how smooth the visual experience remains.</p>
<p>The project runs as a single-page Vite app: <code>npm run dev</code> spins it up in the browser with no background Node services required.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*czq8sns-TG-LDXVhiE1CGw.png" alt="Headless Vitest determinism verification comparing 60 FPS, 30 FPS, and 15 FPS frame schedules for bit-identical positions" style="display:block;margin:0 auto" />

<p><em>Headless Vitest assertions verify identical floating-point positions across 60 FPS, 30 FPS, and 15 FPS schedules.</em></p>
<h3>Proving Determinism with Automated Tests</h3>
<p>Now let's deliver on our opening promise: <strong>same inputs yield identical state, completely independent of frame timing.</strong></p>
<p>You cannot verify this inside a live browser loop: <code>requestAnimationFrame</code> and system timers are inherently non-deterministic.</p>
<p>So we extract the loop's core logic into a pure, headless <code>Accumulator</code> class decoupled from <code>rAF</code>. We feed it an array of frame durations, step the world, and inspect the final state:</p>
<pre><code class="language-ts">import { World } from "./world";

export interface StepperOpts {
  step?: number; // fixed physics step (seconds)
  maxSteps?: number; // max ticks per frame — spiral of death protection
  maxFrame?: number; // upper bound of a single frame (seconds)
}

const EPS = 1e-9; // floating-point tolerance: avoid missing a tick at the acc == step boundary

export class Accumulator {
  acc = 0;
  readonly step: number;
  readonly maxSteps: number;
  readonly maxFrame: number;

  constructor(opts: StepperOpts = {}) {
    this.step = opts.step ?? 1 / 60;
    this.maxSteps = opts.maxSteps ?? 5;
    this.maxFrame = opts.maxFrame ?? 0.25;
  }

  advance(world: World, frameTime: number): { steps: number; alpha: number } {
    if (frameTime &gt; this.maxFrame) frameTime = this.maxFrame;
    this.acc += frameTime;

    let steps = 0;
    while (this.acc &gt;= this.step - EPS &amp;&amp; steps &lt; this.maxSteps) {
      world.snapshot();
      world.step(this.step);
      this.acc -= this.step;
      steps++;
    }
    if (steps === this.maxSteps &amp;&amp; this.acc &gt;= this.step - EPS) this.acc = 0;

    return { steps, alpha: this.acc / this.step };
  }
}

export function runFixed(
  makeWorld: () =&gt; World,
  frames: number[],
  opts?: StepperOpts,
): World {
  const world = makeWorld();
  const acc = new Accumulator(opts);
  for (const ft of frames) acc.advance(world, ft);
  return world;
}

// Old approach in the series — for comparison: direct step with variable dt.
export function runVariable(
  makeWorld: () =&gt; World,
  frames: number[],
  maxFrame = 1,
): World {
  const world = makeWorld();
  for (const ft of frames) world.step(Math.min(ft, maxFrame));
  return world;
}
</code></pre>
<p>That <code>EPS</code> line is the scar of a midnight bug that cost me an hour of debugging. When doing <code>acc += 4 * STEP</code> and subtracting <code>STEP</code> four times, IEEE 754 floating-point inaccuracies occasionally left <code>acc</code> a microscopic hair below <code>STEP</code>. The loop would miss a tick — running 599 ticks instead of 600. And that broke the test. The fix is a tiny epsilon margin (<code>- EPS</code>) in the comparison. A subtle detail, but without it, you'd pull your hair out wondering why a frame occasionally goes missing.</p>
<p>Now for the definitive proof. We simulate the same 10 seconds across three radically different framerate profiles: 60 FPS, 15 FPS, and 30 FPS. We expect the fixed-timestep loop to produce bit-identical results, while the variable-dt version diverges:</p>
<pre><code class="language-ts">import { describe, it, expect } from "vitest";
import { World, createBody } from "../src/world";
import { runFixed, runVariable } from "../src/sim";
import { lerp, vec } from "../src/vec";

const STEP = 1 / 60;
const makeWorld = () =&gt; {
  const w = new World(800, 600, 900);
  w.add(createBody(120, 80, 20, 0.8));
  return w;
};

describe("fixed-timestep loop is deterministic", () =&gt; {
  // Same 10-second total time, three different frame splits:
  const framesA = Array(600).fill(STEP);     // 60 FPS
  const framesB = Array(150).fill(4 * STEP); // 15 FPS (4 ticks per frame)
  const framesC = Array(300).fill(2 * STEP); // 30 FPS (2 ticks per frame)

  it("produces EXACTLY the same state regardless of frame timing", () =&gt; {
    const a = runFixed(makeWorld, framesA).bodies[0];
    const b = runFixed(makeWorld, framesB).bodies[0];
    const c = runFixed(makeWorld, framesC).bodies[0];

    expect(a.pos).toEqual(b.pos);
    expect(a.pos).toEqual(c.pos);
    expect(a.vel).toEqual(b.vel);
  });

  it("variable-dt version diverges (no determinism)", () =&gt; {
    // Before the first wall contact, compare in free fall: semi-implicit
    // Euler's g·dt² term yields different positions depending on dt (without settling).
    const freeA = Array(48).fill(STEP); // 0.8 s, 60 FPS
    const freeB = Array(12).fill(4 * STEP); // 0.8 s, 15 FPS
    const a = runVariable(makeWorld, freeA).bodies[0];
    const b = runVariable(makeWorld, freeB).bodies[0];

    expect(a.pos).not.toEqual(b.pos); // same total duration, different result
  });
});

describe("interpolation math", () =&gt; {
  const a = vec(0, 0);
  const b = vec(10, 20);

  it("alpha=0 yields the previous state", () =&gt; expect(lerp(a, b, 0)).toEqual(vec(0, 0)));
  it("alpha=1 yields the current state", () =&gt; expect(lerp(a, b, 1)).toEqual(vec(10, 20)));
  it("alpha=0.5 yields the exact midpoint", () =&gt; expect(lerp(a, b, 0.5)).toEqual(vec(5, 10)));
});
</code></pre>
<p>The first test confirms our thesis with <code>toEqual</code>: at 60 FPS, 15 FPS, and 30 FPS, the ball's position and velocity vectors match down to the exact floating-point bit.</p>
<p>The second test proves the exact opposite: dividing the same 0.8-second free fall into different <code>dt</code> slices causes the variable-dt simulation to diverge (<code>expect(a.pos).not.toEqual(b.pos)</code>). We measure before the first wall bounce — once a ball bounces and settles on the floor, both systems come to rest in roughly the same place, but the divergence during mid-flight is undeniable due to <code>g · dt²</code>. That two-laptop story from the introduction wasn't an illusion; it is an empirical, testable mathematical fact.</p>
<p>An honest engineering caveat: this determinism guarantee holds as long as you don't hit the spiral-of-death ceiling. If a frame hits <code>MAX_STEPS</code> and clears debt with <code>acc = 0</code>, you drop simulation time, and frame schedules will diverge. In our test suite, we deliberately keep frame chunks below that threshold. In a real game, you only hit that ceiling when hardware is completely choking — at which point keeping the tab responsive matters far more than bit-perfect physics synchronization.</p>
<hr />
<h3>Summary</h3>
<ul>
<li><strong>Variable-dt Instability:</strong> Calling <code>world.step(dt)</code> with variable frame times breaks determinism due to semi-implicit Euler's nonlinear <code>g · dt²</code> term, and causes tunneling at low framerates.</li>
<li><strong>The Metronome Accumulator:</strong> Store elapsed wall-clock time in an accumulator, and advance physics using invariant, fixed <code>STEP</code> slices (<code>while (acc &gt;= STEP)</code>).</li>
<li><strong>Taming the Spiral of Death:</strong> Protect your main thread in two steps: clamp single-frame spikes with <code>MAX_FRAME</code>, cap ticks per frame with <code>MAX_STEPS</code>, and clear accumulated debt when pegged to the ceiling.</li>
<li><strong>Decoupled Update and Render:</strong> Physics ticks at a constant frequency; rendering runs at native display refresh rate. Forcing rendering to follow discrete physics ticks introduces temporal aliasing and micro-stutter.</li>
<li><strong>Alpha Progress Ratio:</strong> Calculate <code>alpha = acc / STEP</code> to find where the renderer sits between the last completed tick and the upcoming tick.</li>
<li><strong>Render Interpolation:</strong> Blend smoothly between previous and current positions using <code>lerp(prev, pos, alpha)</code>. Interpolation renders 1 tick in the past (≈16ms latency) but avoids the jarring prediction snapping of extrapolation.</li>
<li><strong>Testable Determinism:</strong> Split the same total duration into different frame slices; verify that fixed-timestep state passes <code>toEqual</code> while variable-dt produces <code>not.toEqual</code>.</li>
</ul>
<hr />
<h3>Source Code &amp; Live Demo</h3>
<p>The complete source code — engine, game loop, interactive demo, and automated test suite — is open-source on GitHub:</p>
<blockquote>
<p>📦 <strong>GitHub Repository:</strong> <a href="https://github.com/m2-md/fixed-timestep-render-interpolation">github.com/m2-md/fixed-timestep-render-interpolation</a><br />🎮 <strong>Interactive Live Demo:</strong> <a href="https://m2-md.github.io/fixed-timestep-render-interpolation/">m2-md.github.io/fixed-timestep-render-interpolation</a></p>
</blockquote>
<p>What struck me most while writing this project is an interesting architectural paradox: the very move that made the physics engine "correct" (fixed timestep) temporarily made the visuals look <em>worse</em> — forcing us to build an additional layer (render interpolation) to fix it. It felt like taking two steps forward and one step back. But in reality, we had previously entangled two separate concerns — simulation accuracy and display smoothness — into a single variable (<code>dt</code>). Once we untangled that knot, we could solve each problem on its own terms. Great architecture is often like that: decoupling two tightly wound problems so you can speak to each in its native language.</p>
<p>The metronome is ticking, the ball is gliding smoothly. And now, the exact same game plays identically across every machine. ⚙️🧠</p>
<hr />
<h3>📚 Canvas 2D &amp; Game Architecture Series</h3>
<ul>
<li><strong>Part 1 (Published):</strong> <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas</a></li>
<li><strong>Part 2 (Published):</strong> <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8">Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes</a></li>
<li><strong>Part 3 (You are here):</strong> <em>Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript</em></li>
<li><strong>Up Next:</strong> <em>Return the Glass, Not the Trash: Object Pools and Zero-Allocation Loops in Canvas</em></li>
</ul>
<h3>👋 About the Author</h3>
<p>I'm <strong>Mustafa Morbel</strong>, a software engineer with over 17 years of experience writing about modern web technologies, game architectures, browser rendering engines, and AI workflows.</p>
<p>You can inspect all codebases, runnable demos, and test suites across my <a href="https://github.com/mkare">GitHub profile</a>.<br />For new technical guides and architectural deep dives, feel free to connect on <a href="https://www.linkedin.com/in/mustafamorbel/">LinkedIn</a> and <a href="https://x.com/mustafamorbel">X / Twitter (@mustafamorbel)</a>.</p>
<p>Have you run into framerate-dependent physics anomalies or tick jitter in your own projects? I'd love to hear your thoughts in the comments below 🧠💬 — and don't forget to leave a few claps 👏 if you found this breakdown useful!</p>
<hr />
<h3>📦 Want the Bundled Starter Kit &amp; Cheatsheets?</h3>
<p>If you want all 3 TypeScript engines, HiDPI helpers, fixed-timestep loop templates, and vector physics cheatsheets in one clean zip, grab the <a href="https://www.buymeacoffee.com/mkare/e/599265"><strong>TS 2D Canvas Physics &amp; HiDPI Starter Kit</strong></a> (or unlock all kits free with a <a href="https://www.buymeacoffee.com/mkare">Buy Me a Coffee membership</a>).</p>
<ul>
<li><strong>Part 1:</strong> <a href="https://m2-md.github.io/canvas-physics-from-scratch/">How Game Physics Works (Canvas Slingshot Engine)</a> · <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8?source=friends_link&amp;sk=f9c8048fe5b2d513b3c0d26127e97fb4">Free Medium Guide</a></li>
<li><strong>Part 2:</strong> <a href="https://m2-md.github.io/hidpi-canvas-devicepixelratio/">Why Canvas Looks Blurry on Retina (devicePixelRatio)</a> · <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8?source=friends_link&amp;sk=3c3af29a65f3d3238efd567f24c20b00">Free Medium Guide</a></li>
<li><strong>Part 3:</strong> <a href="https://m2-md.github.io/fixed-timestep-render-interpolation/">Metronome Physics (Fixed Timestep &amp; Render Interpolation)</a> · <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11?source=friends_link&amp;sk=ff5390a11e2d97b29e82dc41a6572272">Free Medium Guide</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes]]></title><description><![CDATA[Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link. 🎮 Try the Live Interactive Demo · 📦 GitHub Repo &…]]></description><link>https://mkare.hashnode.dev/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes</link><guid isPermaLink="true">https://mkare.hashnode.dev/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[canvas]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 14:06:00 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium (JavaScript in Plain English).</em> <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8?source=friends_link&amp;sk=3c3af29a65f3d3238efd567f24c20b00"><em>Read on Medium for free via Friend Link</em></a><em>.</em></p>
<p>🎮 <a href="https://m2-md.github.io/hidpi-canvas-devicepixelratio/"><strong>Try the Live Interactive Demo</strong></a> · 📦 <a href="https://github.com/m2-md/hidpi-canvas-devicepixelratio"><strong>GitHub Repo &amp; Vitest Suite</strong></a> · ⚡ <a href="https://www.buymeacoffee.com/mkare/e/599265"><strong>Get the TS 2D Canvas Physics Starter Kit</strong></a></p>
</blockquote>
<img src="https://raw.githubusercontent.com/m2-md/hidpi-canvas-devicepixelratio/main/assets/demo.gif" alt="Interactive Demo Preview" style="display:block;margin:0 auto" />

<img src="https://miro.medium.com/v2/resize:fit:1400/1*5Jsai-aPksJaZYExQDlgIg.png" alt="Side-by-side HTML5 Canvas on Retina: blurry 1x upscaled bitmap vs. razor-sharp HiDPI devicePixelRatio setup" style="display:block;margin:0 auto" />

<p><em>Left: a naive 1x Canvas stretched across 2x Retina hardware pixels blurs thin lines and text. Right: matching backing resolution to devicePixelRatio restores 1:1 sharpness.</em></p>
<h3>The 30-Second Fix (TL;DR)</h3>
<p>If you landed here debugging a blurry <code>&lt;canvas&gt;</code> on a Retina laptop or 4K HiDPI monitor, four rules solve 99% of cases:</p>
<ul>
<li><strong>Multiply</strong> <code>canvas.width</code> <strong>and</strong> <code>canvas.height</code> <strong>by</strong> <code>dpr</code><strong>:</strong> Allocate <code>Math.round(cssW * dpr)</code> by <code>Math.round(cssH * dpr)</code> so the backing bitmap matches physical hardware pixels.</li>
<li><strong>Pin</strong> <code>style.width</code> <strong>and</strong> <code>style.height</code> <strong>in CSS</strong> <code>px</code><strong>:</strong> Keep the layout footprint at <code>cssW</code> and <code>cssH</code> (for example, <code>"300px"</code> by <code>"150px"</code>) so the canvas doesn't visually balloon on the page.</li>
<li><strong>Lock coordinates once with</strong> <code>setTransform</code> <strong>/</strong> <code>scale</code><strong>:</strong> Call <code>ctx.setTransform(dpr, 0, 0, dpr, 0, 0)</code> (or identity reset + <code>ctx.scale(dpr, dpr)</code>) so drawing code stays in CSS coordinates, plus <code>+0.5</code> alignment for crisp <code>1px</code> lines.</li>
<li><strong>Clamp</strong> <code>Math.min(dpr, 2)</code> <strong>for</strong> <code>dpr²</code> <strong>fill-rate:</strong> Pixel count scales quadratically (<code>4×</code> at <code>2x</code>, <code>9×</code> at <code>3x</code>), so cap <code>dpr</code> at <code>2</code> on GPU-heavy 60 FPS scenes.</li>
</ul>
<hr />
<p>Last week, I opened the exact same Canvas code on two different monitors. On my external display, the lines looked razor-sharp. When I dragged the window over to my laptop's built-in Retina display, those same lines went soft — as if I were looking at them through fog. Not a single line of code had changed. The only variable was the screen.</p>
<p>My first instinct was to blame font rendering or overly aggressive anti-aliasing. It was neither.</p>
<p>The real issue lived deeper: what I was drawing onto the canvas and what the physical panel was displaying existed on two different scales. I had requested a width of 300 units, the Retina panel wanted to paint 600 physical dots, and the browser bridged the gap by stretching my image. And stretching a bitmap always means blur.</p>
<p>The mental model for this entire piece is a <strong>currency exchange</strong> problem. Your screen operates in two currencies: the <strong>CSS pixel</strong> (the unit you and the layout engine speak) and the <strong>device pixel</strong> (the actual hardware dots on the panel). On a standard-density display, the exchange rate is 1:1 — no conversion needed. On a Retina or HiDPI screen, the exchange rate jumps to 2x or even 3x. If you draw in the wrong currency, the browser makes up the missing pixels through interpolation. That guesswork shows up on your screen as blurriness.</p>
<p><code>devicePixelRatio</code> is that exact exchange rate. Our roadmap revolves around it: first we'll see why the blur happens, then we'll separate intrinsic resolution from display size and lock the exchange rate once with <code>ctx.scale</code>, neutralize two hidden enemies of sharpness (half-pixel alignment and blurry image smoothing), catch dynamic exchange-rate changes when dragging windows across monitors, and finally calculate — and benchmark — the <code>dpr²</code> fill-rate cost of all that crispness.</p>
<p>Let me start with a confession, because it's the reason this article exists. In the previous article of this series, where we built a 2D physics engine from scratch (<a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">How Game Physics Works</a>), I wrote: <em>"When the canvas's internal resolution matches the screen 1:1, CSS scaling disappears."</em> That sentence isn't wrong, but it is incomplete. In that project, I set the canvas width to <code>window.innerWidth</code> — which is measured in CSS pixels. On a Retina screen, there are far fewer CSS pixels than device pixels. So what I called "1:1" was actually half resolution, and the game rendered slightly soft on Retina displays. Nobody noticed because circles and flat fills forgive blurriness. Thin 1px lines and small typography do not. This article closes that gap.</p>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*3n_hP2AEKfca3lcC0ClvLQ.png" alt="Diagram comparing 1x standard display pixels against 2x Retina CSS-to-device pixel mapping and upscaling blur" style="display:block;margin:0 auto" />

<p><em>Why Retina blurs an unscaled Canvas: 1 CSS pixel spans a 2×2 grid of physical device pixels, forcing the browser to upscale a 1x bitmap via bilinear interpolation.</em></p>
<hr />
<h3>Why Is It Blurry? CSS Pixels vs. Device Pixels</h3>
<p>First, let's cleanly separate the two currencies.</p>
<p>A <strong>CSS pixel</strong> is an abstract layout unit. When you write <code>width: 300px</code>, you are telling the browser: <em>"Make this box 300 CSS pixels wide."</em> A <strong>device pixel</strong>, on the other hand, is physical: an actual light-emitting subpixel cluster on the hardware panel. On older monitors, these two matched 1:1 — one CSS pixel mapped to exactly one device pixel. The exchange rate was <code>1</code>.</p>
<p>Retina displays intentionally broke that equality to make text and UI elements look sharper: pack twice as many physical dots into the same physical inch without shrinking the user interface. As a result, a single CSS pixel spans a <code>2×2 = 4</code> grid of device pixels. HTML text and SVGs get this sharpness for free because the browser re-rasterizes them from vector paths at native device resolution.</p>
<p>Canvas does not get it for free. Because a <code>&lt;canvas&gt;</code> is a bitmap. It only has as many pixels as you explicitly allocate in its backing buffer.</p>
<p>Think of it this way. When you write <code>&lt;canvas width="300" height="150"&gt;</code>, you allocate a backing bitmap of <code>300×150</code> pixels. On a 2x Retina display, CSS lays out that element across a <code>300</code> CSS-pixel region — which physically spans <code>600</code> device pixels on the glass. The browser is holding 300 pixels of data and has to fill 600 physical pixels. It bridges the gap via <strong>upscaling</strong>, blending neighboring pixels together through bilinear interpolation. That blending is the blur you see.</p>
<p>In a single sentence: <strong>you produced too few pixels and stretched them across a wide physical area, so the browser filled the gaps with blur.</strong></p>
<hr />
<h3><code>devicePixelRatio</code>: The Exchange Rate Between Two Currencies</h3>
<p><code>window.devicePixelRatio</code> is the live exchange rate provided by the browser. Its definition is simple: how many device pixels correspond to a single CSS pixel.</p>
<ul>
<li><strong>Standard display:</strong> <code>devicePixelRatio === 1</code> (<code>1 CSS px = 1 device px</code>)</li>
<li><strong>Most Retina / HiDPI laptops:</strong> <code>devicePixelRatio === 2</code> (<code>1 CSS px = 2 device px</code>)</li>
<li><strong>High-density mobile screens:</strong> <code>devicePixelRatio === 3</code></li>
</ul>
<p>Moreover, this value isn't always a clean integer. When a user zooms the browser page (or uses fractional OS scaling on Windows/Linux), you'll encounter values like <code>1.25</code> or <code>1.5</code>. Hardcoding assumptions like <em>"dpr is either 1 or 2"</em> plants a future bug. Treat the exchange rate as an arbitrary floating-point number and use whatever the browser reports.</p>
<p>Our first step is writing pure functions to convert dimensions between the two currencies. These functions don't touch the DOM or Canvas, which makes them trivial to unit-test later:</p>
<pre><code class="language-ts">// scale.ts — pure conversion math, zero DOM dependencies
export interface Size {
  w: number;
  h: number;
}

// CSS dimensions -&gt; device pixels (for canvas.width / canvas.height)
// Rounding is mandatory: canvas.width must be an integer and truncates decimals.
export function deviceSize(cssW: number, cssH: number, dpr: number): Size {
  return {
    w: Math.round(cssW * dpr),
    h: Math.round(cssH * dpr),
  };
}

// Convert a single scalar length between currencies (apply rate / invert rate)
export function cssToDevice(px: number, dpr: number): number {
  return px * dpr;
}

export function deviceToCss(px: number, dpr: number): number {
  return px / dpr;
}
</code></pre>
<p>Pay close attention to <code>Math.round</code> inside <code>deviceSize</code>. <code>canvas.width</code> is an unsigned integer attribute; if you pass a floating-point number, the browser silently floors it. When fluid layouts produce fractional CSS dimensions like <code>300.5</code> (or when <code>dpr</code> is <code>1.25</code>), explicit rounding keeps sub-pixel truncation from accumulating into visible layout drift.</p>
<p>Now that we have the exchange rate and our conversion helpers, let's wire them into a real Canvas setup.</p>
<hr />
<h3>Intrinsic Resolution vs. CSS Size: <code>canvas.width</code> vs. <code>style.width</code></h3>
<p>Here is the fundamental truth that confuses almost everyone when they first meet <code>&lt;canvas&gt;</code>: <strong>a canvas element has two completely independent sizes.</strong></p>
<ol>
<li><strong>Intrinsic resolution (backing buffer size):</strong> <code>canvas.width</code> and <code>canvas.height</code>. This dictates how many actual pixels exist inside the bitmap grid. We must think of this in <strong>device pixels</strong>.</li>
<li><strong>Display size (layout size):</strong> <code>canvas.style.width</code> and <code>canvas.style.height</code>. This dictates how much space the element occupies on the web page. We think of this in <strong>CSS pixels</strong>.</li>
</ol>
<p>Naive code conflates the two — or sets only <code>canvas.width</code> and lets the browser infer the CSS size. The entire secret to a razor-sharp canvas is setting both intentionally to different values: <strong>multiply the intrinsic resolution by</strong> <code>dpr</code> <strong>to match device pixels, and keep the display size in CSS pixels.</strong></p>
<pre><code class="language-ts">// hidpi.ts — Canvas / DOM setup layer
import { deviceSize } from "./scale";

export function setupHiDPICanvas(
  canvas: HTMLCanvasElement,
  cssW: number,
  cssH: number,
  dpr: number = window.devicePixelRatio || 1,
): CanvasRenderingContext2D {
  const { w, h } = deviceSize(cssW, cssH, dpr);

  // Intrinsic resolution: device pixels (actual bitmap dot count)
  canvas.width = w;
  canvas.height = h;

  // Display size: CSS pixels (visual footprint on the page)
  canvas.style.width = `${cssW}px`;
  canvas.style.height = `${cssH}px`;

  const ctx = canvas.getContext("2d");
  if (!ctx) throw new Error("Failed to acquire 2D context");

  // Lock the exchange rate once: keep drawing coordinates in CSS space
  ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform matrix first
  ctx.scale(dpr, dpr);                // then scale by dpr
  return ctx;
}
</code></pre>
<p>What happens on a Retina screen (<code>dpr = 2</code>) when this runs? <code>canvas.width</code> becomes <code>600</code> (the backing bitmap is genuinely 600 dots wide), while <code>canvas.style.width</code> stays <code>"300px"</code> (occupying 300 CSS pixels in the layout). The browser no longer has anything to stretch: it has 600 bitmap pixels in hand and 600 physical device pixels to fill on the screen. The 1:1 hardware mapping is restored, and the blur vanishes.</p>
<p>Wait — there's a catch. Our backing bitmap is now a <code>600×300</code> coordinate grid. Does that mean we have to rewrite all our drawing logic for a 600-unit world and manually multiply every coordinate by <code>dpr</code>? No. The clean fix is already sitting in the last two lines of <code>setupHiDPICanvas</code>.</p>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*3FW21ZNOGJWzOa_7RElpdQ.png" alt="Architecture diagram separating HTML5 Canvas intrinsic backing buffer (canvas.width) from CSS layout size" style="display:block;margin:0 auto" />

<p><em>The tale of two sizes: canvas.width allocates the device-pixel backing buffer (600×300 at 2x), while canvas.style.width pins the CSS layout footprint (300×150px).</em></p>
<hr />
<h3><code>ctx.scale</code>: Lock the Exchange Rate Once, Forget the Rest</h3>
<p>The <code>ctx.scale(dpr, dpr)</code> call is the heart of this pattern. In plain English, it tells the 2D context: <em>"From now on, I will hand you all coordinates in CSS pixels — you handle multiplying them into device pixels behind the scenes."</em></p>
<p>In our currency metaphor, instead of calculating the exchange rate on every single item you buy, you configure the cash register once to price everything in CSS currency and convert automatically at checkout.</p>
<p>Let's make it concrete. At <code>dpr = 2</code>, the backing bitmap is <code>600</code> pixels wide. You want to place a dot at the horizontal center, so you write <code>ctx.fillRect(150, 75, 1, 1)</code> in CSS space. Thanks to <code>ctx.scale(2, 2)</code>, that call maps to <code>(300, 150)</code> in device space and paints a <code>2×2</code> block of physical pixels. You wrote <code>150</code>, the canvas painted at <code>300</code>, and your drawing code never had to care.</p>
<p>The payoff is huge: <strong>your rendering code becomes completely</strong> <code>dpr</code><strong>-agnostic.</strong> The exact same <code>draw()</code> function runs unmodified on 1x, 2x, and 3x displays. The exchange rate is applied once during setup, and the rest of your codebase forgets it exists:</p>
<pre><code class="language-ts">// Minimal usage example (the full interactive demo is further below)
import { setupHiDPICanvas } from "./hidpi";

const canvas = document.querySelector&lt;HTMLCanvasElement&gt;("#scene")!;
const ctx = setupHiDPICanvas(canvas, 300, 150);

// This function has zero knowledge of devicePixelRatio.
// Every coordinate is expressed in CSS pixels; the exchange rate is already locked.
function draw(ctx: CanvasRenderingContext2D): void {
  ctx.clearRect(0, 0, 300, 150);
  ctx.fillStyle = "#7c3aed";
  ctx.font = "13px system-ui";
  ctx.fillText("crisp text", 20, 30); // 20, 30 -&gt; CSS pixels
  ctx.strokeRect(20, 50, 260, 80);
}
draw(ctx);
</code></pre>
<p>This separation looks like a small convenience in a 15-line snippet, but as a project grows, it is worth its weight in gold. <code>devicePixelRatio</code> never leaks into your physics, layout, or hit-testing logic. Device space lives in exactly two lines of code: assigning <code>canvas.width</code> and calling <code>ctx.scale</code>. When a scaling bug appears, you know where to look.</p>
<hr />
<h3>Two Hidden Enemies of Sharpness: Half-Pixels and Blurry Scaling</h3>
<p>Suppose you configured the exchange rate properly. Your canvas backing buffer now matches the hardware 1:1. Yet you draw a thin <code>1px</code> line, and it still renders as a pale, 2-pixel-wide gray smudge. Why?</p>
<p>This is a classic Canvas quirk that exists independently of <code>dpr</code> — though HiDPI makes it even sneakier.</p>
<p>Canvas integer coordinates point to the <strong>grid lines between pixels</strong>, not the centers of the pixels. When you set <code>ctx.lineWidth = 1</code> and draw a vertical line at <code>x = 20</code>, the path sits directly on the boundary between pixel <code>19</code> and pixel <code>20</code>. A 1-pixel-wide stroke expands half a pixel to the left (into pixel 19) and half a pixel to the right (into pixel 20). Because a screen cannot illuminate half a pixel, the anti-aliasing rasterizer paints both neighboring pixels at 50% opacity.</p>
<p>The result? A washed-out line twice as thick and half as contrasty as what you asked for.</p>
<p>The fix is offsetting 1px strokes onto the <strong>center</strong> of the pixel grid by aligning to <code>.5</code>. When you draw at <code>20.5</code>, the 1-pixel stroke spans from <code>20.0</code> to <code>21.0</code>, completely filling pixel 20 with a crisp, 100%-opaque line:</p>
<pre><code class="language-ts">// 0.5 offset alignment for crisp 1px strokes.
// Integer -&gt; +0.5 (centered); values already at .5 stay unchanged.
export function alignHalfPixel(x: number): number {
  return Math.floor(x) + 0.5;
}
</code></pre>
<p>Here is how you use it:</p>
<pre><code class="language-ts">import { alignHalfPixel } from "./scale";

// Blurry: path sits on the boundary between pixels, bleeding across two columns
ctx.beginPath();
ctx.moveTo(40, 10);
ctx.lineTo(40, 140);
ctx.stroke();

// Crisp: path sits dead-center inside the pixel column
const x = alignHalfPixel(40); // 40.5
ctx.beginPath();
ctx.moveTo(x, 10);
ctx.lineTo(x, 140);
ctx.stroke();
</code></pre>
<p>The second enemy is <strong>image scaling interpolation</strong>. When you draw a small bitmap scaled up onto a canvas, the browser defaults to bilinear filtering (<code>imageSmoothingEnabled = true</code>), blending pixels together. For photographs, that's what you want. For pixel-art sprites, it destroys crisp pixel edges and turns your art into mush. To preserve hard edges, disable smoothing:</p>
<pre><code class="language-ts">ctx.imageSmoothingEnabled = false; // keep pixel-art edges razor-sharp
</code></pre>
<p>Our repository's demo uses this flag in two different places for two opposite purposes — worth pointing out now so it doesn't trip you up. Right before drawing the pixel-art grid at the bottom of the scene, we set <code>imageSmoothingEnabled = false</code> to keep the grid sharp. On the naive comparison canvas, we deliberately set <code>imageSmoothingEnabled = true</code> so we can accurately simulate the browser's blurry upscaling on any monitor. Same flag, two opposite goals.</p>
<blockquote>
<p><strong>Gotcha (learned the hard way while writing our WebGL2 sprite batching article):</strong> Every time you assign to <code>canvas.width</code> or <code>canvas.height</code>, the entire 2D rendering context resets to factory defaults — including <code>imageSmoothingEnabled</code>, <code>font</code>, <code>fillStyle</code>, and the transform matrix. If you resize a canvas without re-applying <code>ctx.imageSmoothingEnabled = false</code>, your sprites suddenly turn blurry and you spend half an hour wondering why. Make it a reflex: <strong>whenever you resize the canvas, refresh your context state.</strong></p>
</blockquote>
<hr />
<h3>Dragging Across Monitors: <code>dpr</code> Can Change at Runtime</h3>
<p>Up to this point, we read <code>window.devicePixelRatio</code> once at startup and treated it like a constant. It isn't.</p>
<p>If a user drags their browser window from a Retina MacBook screen onto a standard 1080p external monitor, <code>devicePixelRatio</code> drops from <code>2</code> to <code>1</code> on the fly. If they hit <code>Cmd + Plus</code> to zoom the page, <code>dpr</code> becomes fractional. When that happens, your 600-dot canvas is suddenly crammed into a 300-dot physical region (or vice versa). Scale breaks, and sharpness disappears.</p>
<p>How do we catch that transition? A standard <code>window.addEventListener("resize", ...)</code> doesn't reliably fire when moving a window between monitors of different pixel densities if the CSS viewport dimensions don't change. The right tool is <code>window.matchMedia</code> with a <code>dppx</code> (dots per pixel) resolution query.</p>
<p>The trick is clever: we embed the <em>current</em> <code>dpr</code> value into a media query string like <code>(resolution: 2dppx)</code>. That query matches as long as <code>dpr</code> stays at <code>2</code>. The instant <code>dpr</code> changes to anything else, the media query stops matching and fires its <code>change</code> event. Inside the handler, we invoke our callback with the new <code>dpr</code> and register a fresh media query for the new value:</p>
<pre><code class="language-ts">// Listens for devicePixelRatio changes; invokes cb(newDpr) on every transition.
// Returns an unsubscribe cleanup function.
export function watchDprChange(cb: (dpr: number) =&gt; void): () =&gt; void {
  let media: MediaQueryList | null = null;

  const handler = () =&gt; {
    cb(window.devicePixelRatio || 1);
    listen(); // register a fresh query for the new dpr value
  };

  const listen = () =&gt; {
    const dpr = window.devicePixelRatio || 1;
    // Matches only while dpr equals the current value.
    // As soon as dpr shifts, match breaks -&gt; "change" fires.
    media = window.matchMedia(`(resolution: ${dpr}dppx)`);
    media.addEventListener("change", handler, { once: true });
  };

  listen();
  return () =&gt; media?.removeEventListener("change", handler);
}
</code></pre>
<p>The <code>{ once: true }</code> option is deliberate. Each <code>MediaQueryList</code> instance is single-use for the current exchange rate; once <code>dpr</code> shifts, we discard the old query and bind a new one for the updated <code>dppx</code> value.</p>
<p>Once we catch a change, we need to reconfigure the canvas. Remember one critical detail: assigning to <code>canvas.width</code> — even if you assign the exact same number it already holds — wipes the bitmap clean. To avoid needlessly clearing frames, we check whether the target device dimensions actually changed before touching <code>canvas.width</code>:</p>
<pre><code class="language-ts">// NOTE: This helper lives in the repo for responsive production layouts
// (e.g., width: 100% canvases driven by ResizeObserver or render loops).
// Reconfigures the canvas only when backing dimensions genuinely change.
// Returns true if the canvas was resized.
export function resizeToDisplaySize(
  canvas: HTMLCanvasElement,
  ctx: CanvasRenderingContext2D,
  cssW: number,
  cssH: number,
  dpr: number = window.devicePixelRatio || 1,
): boolean {
  const { w, h } = deviceSize(cssW, cssH, dpr);
  if (canvas.width === w &amp;&amp; canvas.height === h) {
    return false; // already at target resolution, do not touch
  }

  canvas.width = w;
  canvas.height = h;
  canvas.style.width = `${cssW}px`;
  canvas.style.height = `${cssH}px`;

  // Reset transform and apply new scale in a single call:
  // (dpr, 0, 0, dpr, 0, 0) = identity reset + scale(dpr, dpr).
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  return true;
}
</code></pre>
<p>Notice <code>ctx.setTransform(dpr, 0, 0, dpr, 0, 0)</code>. It combines <code>setTransform(1, 0, 0, 1, 0, 0)</code> and <code>scale(dpr, dpr)</code> into a single operation. Why prefer <code>setTransform</code> over <code>scale</code>? Because <code>ctx.scale()</code> multiplies onto whatever transform matrix is currently active. Even though setting <code>canvas.width</code> implicitly resets the transform to identity, calling <code>setTransform</code> explicitly guarantees you will never suffer from compounding scale bugs (<code>2x -&gt; 4x -&gt; 8x</code>) if someone refactors the code later.</p>
<hr />
<h3>Measuring the Cost: <code>dpr²</code> Fill-Rate</h3>
<p>So far, I've talked about HiDPI sharpness as if it were a free lunch. It isn't. Let's look at the bill.</p>
<p>On a 2x Retina screen, your canvas holds twice as many pixels horizontally and twice as many vertically. That means <code>2 × 2 = 4</code> times as many total pixels. On a <code>dpr = 3</code> mobile screen, it's <code>3 × 3 = 9</code> times as many pixels. Because the exchange rate applies across two dimensions simultaneously, the pixel count scales <strong>quadratically</strong>, not linearly:</p>
<pre><code class="language-ts">// Total painted pixels scale quadratically with dpr.
// dpr=2 -&gt; 4x pixels, dpr=3 -&gt; 9x pixels.
export function pixelRatio(dpr: number): number {
  return dpr * dpr;
}
</code></pre>
<p>Why does this matter? Because the number of pixels the GPU (or CPU software rasterizer) must shade and composite every frame — your <strong>fill-rate</strong> — multiplies by that exact factor. Same scene, same number of draw calls, four to nine times the pixel workload.</p>
<p>Let's put real numbers on the table. Picture a modest <code>400×300</code> CSS-pixel canvas rendering at 60 FPS. The last two columns below aren't textbook arithmetic — they are actual measurements from our benchmark suite running on my machine:</p>
<pre><code class="language-text">dpr  Backing Res   Px / Frame   Px / Sec    ms/frame   vs 1x
---  -----------  -----------  ---------  ----------  ------
  1      400×300      120,000       7.2M    0.186 ms   0.90×
  2      800×600      480,000      28.8M    0.784 ms   3.78×
  3     1200×900    1,080,000      64.8M    1.742 ms   8.40×
</code></pre>
<p>Pure arithmetic predicts <code>1× / 4× / 9×</code>; real memory-fill measurement clocks in at <code>0.90× / 3.78× / 8.40×</code>. Close, but not identical — and in the next section we'll unpack why.</p>
<p>At <code>dpr = 3</code>, the rasterizer fills nine times as many pixels as at <code>1x</code>. On a simple 2D UI widget, you won't feel it. On a full-screen fragment shader, heavy Gaussian blurs, <code>ctx.shadowBlur</code>, or thousands of overlapping alpha-blended sprites, that <code>9×</code> multiplier will drop a smooth 60 FPS animation straight down to 20 FPS.</p>
<p>That is why many production WebGL engines and games clamp their effective <code>devicePixelRatio</code> using <code>Math.min(window.devicePixelRatio, 2)</code>. The reasoning is a pragmatic trade-off: the naked eye can barely distinguish <code>2x</code> from <code>3x</code> on a phone screen held at arm's length, yet the fill-rate cost jumps from <code>4×</code> to <code>9×</code>. Capping at <code>2</code> saves both battery life and frame budgets:</p>
<pre><code class="language-ts">// Clamp dpr on fill-rate-heavy scenes: negligible visual loss, massive GPU savings
const cappedDpr = Math.min(window.devicePixelRatio || 1, 2);
const ctx = setupHiDPICanvas(canvas, 400, 300, cappedDpr);
</code></pre>
<p>The rule of thumb: for text-heavy, mostly static diagrams or UI editors, use the full native <code>dpr</code>. For 60 FPS games and full-bleed effects, clamping at <code>2</code> is almost always the right engineering call. Sharpness is a spectrum, not a binary target.</p>
<hr />
<h3>Backing Arithmetic with Measurement: <code>npm run bench</code></h3>
<p>The left half of our table above is just multiplication (<code>400 × 300 × 9 = 1,080,000</code>). Nobody argues with multiplication, and nobody is visceral-level convinced by it either. <em>"The pixel count goes up 9x"</em> is one claim; <em>"your frame work actually gets ~9x more expensive"</em> is another. If we claim the second, we should measure it.</p>
<p>Here is the constraint: I wanted the benchmark to run in a headless Node environment so anyone who clones the repo and runs <code>npm run bench</code> gets reproducible numbers without opening a browser. Node doesn't have a GPU or <code>fillRect</code>.</p>
<p>The solution is remembering what filling a canvas actually is at the lowest level: writing <code>width × height × 4</code> RGBA bytes into a contiguous memory buffer. We can perform that exact work on a <code>Uint8ClampedArray</code> (the backing store type of <code>ImageData</code>): zero the buffer to simulate <code>clearRect</code>, then write an opaque RGBA color across every pixel to simulate a full-canvas <code>fillRect</code>. We aren't measuring absolute GPU clock speed — we are measuring how memory bandwidth and fill time scale as <code>dpr</code> climbs from <code>1</code> to <code>3</code>.</p>
<p>First, the arithmetic table generator in <code>bench.ts</code>:</p>
<pre><code class="language-ts">// bench.ts — both arithmetic and empirical proof of dpr² fill-rate scaling
import { deviceSize, pixelRatio } from "./scale";

export interface FillRateRow {
  dpr: number;
  devW: number;
  devH: number;
  perFrame: number;  // device pixels painted per frame
  perSecond: number; // multiplied by target FPS
}

// Pure arithmetic: generates the theoretical fill-rate table
export function fillRateTable(
  cssW: number,
  cssH: number,
  fps: number,
  dprs: number[],
): FillRateRow[] {
  return dprs.map((dpr) =&gt; {
    const { w, h } = deviceSize(cssW, cssH, dpr);
    const perFrame = w * h;
    return { dpr, devW: w, devH: h, perFrame, perSecond: perFrame * fps };
  });
}
</code></pre>
<p>Next, the empirical measurement. Notice that we allocate the <code>Uint8ClampedArray</code> <strong>once</strong> outside the timed loop; we want to measure per-frame pixel fill cost, not garbage-collector allocation overhead:</p>
<pre><code class="language-ts">export interface CostRow {
  dpr: number;
  devW: number;
  devH: number;
  msPerFrame: number;
  vs1x: number;     // measured cost ratio relative to dpr=1 baseline
  expected: number; // pixelRatio(dpr): theoretical dpr² ratio
}

// Empirical measurement: clear + fill RGBA bytes for every device pixel each frame.
// Buffer is allocated once outside the timer so allocation cost doesn't skew results.
export function measureFillCost(
  cssW: number,
  cssH: number,
  dpr: number,
  frames: number,
): { devW: number; devH: number; msPerFrame: number } {
  const { w, h } = deviceSize(cssW, cssH, dpr);
  const buf = new Uint8ClampedArray(w * h * 4);
  const n = buf.length;

  const start = performance.now();
  for (let f = 0; f &lt; frames; f++) {
    // clearRect equivalent: zero the entire buffer
    buf.fill(0);
    // fillRect equivalent: write opaque RGBA color across all pixels
    for (let i = 0; i &lt; n; i += 4) {
      buf[i] = 124;
      buf[i + 1] = 58;
      buf[i + 2] = 237;
      buf[i + 3] = 255;
    }
  }
  const total = performance.now() - start;
  return { devW: w, devH: h, msPerFrame: total / frames };
}
</code></pre>
<p>Finally, <code>costTrend</code> normalizes each <code>dpr</code> run against a <code>dpr = 1</code> baseline and puts the measured ratio right next to the theoretical <code>dpr²</code> expectation:</p>
<pre><code class="language-ts">export function costTrend(
  cssW: number,
  cssH: number,
  frames: number,
  dprs: number[],
): CostRow[] {
  const base = measureFillCost(cssW, cssH, 1, frames).msPerFrame;
  return dprs.map((dpr) =&gt; {
    const m = measureFillCost(cssW, cssH, dpr, frames);
    return {
      dpr,
      devW: m.devW,
      devH: m.devH,
      msPerFrame: m.msPerFrame,
      vs1x: m.msPerFrame / base,
      expected: pixelRatio(dpr),
    };
  });
}
</code></pre>
<p>Running <code>npm run bench</code> (<code>vite-node src/bench-cli.ts</code>) produces the following output:</p>
<pre><code class="language-text">fill-rate table (400×300 CSS, 60 FPS) — pure arithmetic
  dpr  intrinsic res   pixels/frame   pixels/sec
    1        400×300        120,000         7.2M
    2        800×600        480,000        28.8M
    3       1200×900      1,080,000        64.8M

measured cost (clear+fill, 200 frames) — dpr² verification
  dpr  intrinsic res   ms/frame   vs 1x ratio   expected dpr²
    1        400×300      0.186         0.90×              1×
    2        800×600      0.784         3.78×              4×
    3       1200×900      1.742         8.40×              9×
</code></pre>
<p>Let's read this output honestly, because the deviations are the most instructive part.</p>
<p>First, look at the <code>dpr = 1</code> row: expected <code>1×</code>, measured <code>0.90×</code>. How can <code>1x</code> deviate from itself? Because <code>costTrend</code> measures the <code>base</code> time in an initial <code>measureFillCost(..., 1, ...)</code> call, and then measures <code>dpr = 1</code> a second time inside the <code>dprs.map</code> loop. Between the first call and the second, V8's JIT compiler warms up the loop, making the second pass <del>10% faster. That <code>0.90×</code> isn't a bug — it tells us our <strong>measurement noise floor</strong> (</del>5–10% variance across consecutive runs).</p>
<p>With that ruler in hand, <code>3.78×</code> and <code>8.40×</code> sit right within 5–7% of the theoretical <code>4×</code> and <code>9×</code> targets. Why slightly below? At <code>dpr = 1</code>, the buffer is <code>480 KB</code> — it fits comfortably inside CPU cache, so fixed loop and function-call overhead represents a larger slice of the total time. At <code>dpr = 3</code>, the buffer grows to <code>4.3 MB</code>, amortizing fixed overhead while pure memory bandwidth dominates.</p>
<p>The takeaway is unmistakable: moving from <code>dpr = 1</code> to <code>2</code> doesn't double the work — it nearly <strong>quadruples</strong> it. Moving to <code>3</code> multiplies it nearly <strong>ninefold</strong>. Whenever someone on your team asks why a Canvas page feels sluggish on a 4K or Retina display, running <code>npm run bench</code> settles the conversation in two seconds.</p>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*MI8f1HWM32F7Dgc1HGO7Og.png" alt="Chart of quadratic dpr² Canvas fill-rate scaling across 1x, 2x, and 3x displays (0.90x, 3.78x, and 8.40x cost)" style="display:block;margin:0 auto" />

<p><em>Quadratic fill-rate scaling in practice: moving from 1x to 2x quadruples painted pixels (3.78× measured), and 3x multiplies per-frame fill cost nearly ninefold (8.40×).</em></p>
<hr />
<h3>Testing What Can Be Tested: Pure Scaling Math</h3>
<p>In a headless Vitest environment, there is no physical monitor, no hardware compositor, and no <code>window.devicePixelRatio</code>. You cannot visually unit-test <code>ctx.scale</code>. So what <em>do</em> we test?</p>
<p>Where the bugs actually live. And bugs almost never live inside the browser's <code>ctx.scale</code> implementation — they live in the numbers we feed into it: rounding fractional widths, applying and inverting exchange rates, half-pixel grid snapping, and quadratic area ratios. Because we extracted all of that math into pure functions taking <code>dpr</code> as an explicit parameter, our tests are 100% deterministic:</p>
<pre><code class="language-ts">import { describe, it, expect } from "vitest";
import {
  deviceSize,
  cssToDevice,
  deviceToCss,
  alignHalfPixel,
  pixelRatio,
} from "../src/scale";

describe("deviceSize", () =&gt; {
  it("preserves CSS dimensions at dpr=1", () =&gt; {
    expect(deviceSize(300, 150, 1)).toEqual({ w: 300, h: 150 });
  });

  it("doubles each edge at dpr=2", () =&gt; {
    expect(deviceSize(300, 150, 2)).toEqual({ w: 600, h: 300 });
  });

  it("triples each edge at dpr=3", () =&gt; {
    expect(deviceSize(400, 300, 3)).toEqual({ w: 1200, h: 900 });
  });

  it("rounds fractional CSS dimensions to nearest integer", () =&gt; {
    // 300.4 * 1.5 = 450.6 -&gt; 451 ; 150.2 * 1.5 = 225.3 -&gt; 225
    expect(deviceSize(300.4, 150.2, 1.5)).toEqual({ w: 451, h: 225 });
  });
});
</code></pre>
<p>Currency conversion deserves a round-trip property test: converting from CSS pixels to device pixels and back must return the original number:</p>
<pre><code class="language-ts">describe("cssToDevice / deviceToCss", () =&gt; {
  it("cssToDevice multiplies by the exchange rate", () =&gt; {
    expect(cssToDevice(100, 2)).toBe(200);
    expect(cssToDevice(100, 3)).toBe(300);
  });

  it("deviceToCss inverts the exchange rate", () =&gt; {
    expect(deviceToCss(200, 2)).toBe(100);
  });

  it("round-trips back to the starting value across dpr values", () =&gt; {
    for (const dpr of [1, 1.5, 2, 3]) {
      const px = 137;
      expect(deviceToCss(cssToDevice(px, dpr), dpr)).toBeCloseTo(px);
    }
  });
});
</code></pre>
<p>Half-pixel alignment is a one-liner, yet it's where 1px stroke bugs hide. We pin down both behaviors — integers shift to <code>.5</code>, and values already at <code>.5</code> stay untouched:</p>
<pre><code class="language-ts">describe("alignHalfPixel", () =&gt; {
  it("centers integers onto the half-pixel grid", () =&gt; {
    expect(alignHalfPixel(40)).toBe(40.5);
    expect(alignHalfPixel(0)).toBe(0.5);
  });

  it("leaves values already at .5 unchanged", () =&gt; {
    expect(alignHalfPixel(40.5)).toBe(40.5);
  });

  it("floors fractional coordinates before centering to .5", () =&gt; {
    expect(alignHalfPixel(40.2)).toBe(40.5);
    expect(alignHalfPixel(40.9)).toBe(40.5);
  });
});
</code></pre>
<p>And finally, our quadratic pixel ratio:</p>
<pre><code class="language-ts">describe("pixelRatio", () =&gt; {
  it("dpr=2 means 4x total pixels", () =&gt; {
    expect(pixelRatio(2)).toBe(4);
  });

  it("dpr=3 means 9x total pixels", () =&gt; {
    expect(pixelRatio(3)).toBe(9);
  });

  it("doubling dpr quadruples the pixel count", () =&gt; {
    const dpr = 1.5;
    expect(pixelRatio(dpr * 2)).toBeCloseTo(pixelRatio(dpr) * 4);
  });
});
</code></pre>
<p>That last assertion turns our entire fill-rate warning into a single mathematical invariant: <strong>doubling</strong> <code>dpr</code> <strong>quadruples the pixel count.</strong> <code>npm test</code> runs all 13 assertions in milliseconds.</p>
<img src="https://miro.medium.com/v2/resize:fit:1400/1*gTuvSzduOR2Jn93y-YDEEQ.png" alt="Pure TypeScript scaling pipeline isolating deviceSize, alignHalfPixel, and pixelRatio for Vitest unit testing" style="display:block;margin:0 auto" />

<p><em>Extracting pure coordinate math from DOM and Canvas state lets Vitest verify rounding, currency round-trips, 0.5px snapping, and dpr² invariants deterministically.</em></p>
<hr />
<h3>The Demo: Two Canvases Side by Side</h3>
<p>The interactive demo in the repository puts both currencies side by side. Two canvases render the exact same scene: <code>11px</code> typography, <code>1px</code> vertical and horizontal lines, a circle outline, and a pixel-art grid. The left canvas shows the naive setup; the right canvas runs through <code>setupHiDPICanvas</code>.</p>
<p>One note of engineering honesty: if I left the naive canvas <em>literally</em> naive (<code>canvas.width = CSS_W</code>), you would only see the blur if you happened to read this on a Retina display; on a standard 1x monitor, both canvases would look identical. To make the comparison visible on any screen, the naive canvas renders the scene once into a <code>1x</code> offscreen canvas (<code>320×200</code>) and then stretches that bitmap up to the active <code>dpr</code> resolution with <code>imageSmoothingEnabled = true</code>. That faithfully reproduces what the browser compositor does to an unscaled canvas on a HiDPI screen, while letting you toggle between <code>1×</code>, <code>2×</code>, and <code>3×</code> on any monitor:</p>
<pre><code class="language-ts">// src/main.ts
import { setupHiDPICanvas, watchDprChange } from "./hidpi";
import { deviceSize, alignHalfPixel, pixelRatio } from "./scale";

const CSS_W = 320;
const CSS_H = 200;

const naive = document.querySelector&lt;HTMLCanvasElement&gt;("#naive")!;
const hidpi = document.querySelector&lt;HTMLCanvasElement&gt;("#hidpi")!;
const hud = document.querySelector&lt;HTMLDivElement&gt;("#hud")!;

// Offscreen 1x buffer to simulate browser upscaling blur on the naive canvas
const offscreen = document.createElement("canvas");
offscreen.width = CSS_W;
offscreen.height = CSS_H;
const offCtx = offscreen.getContext("2d")!;

let activeDpr = 1;
</code></pre>
<p>The <code>drawScene</code> function puts every technique from this article to the test — and notice that it never references <code>dpr</code> once:</p>
<pre><code class="language-ts">// Shared vector scene: thin 1px lines, small text, circle arc, and pixel grid.
// All coordinates are in CSS space; 1px strokes use alignHalfPixel.
function drawScene(ctx: CanvasRenderingContext2D, label: string): void {
  ctx.clearRect(0, 0, CSS_W, CSS_H);

  // Small typography (the ultimate sharpness test)
  ctx.fillStyle = "#1c1917";
  ctx.font = "11px system-ui";
  ctx.fillText(label, 14, 22);

  ctx.font = "12px system-ui";
  ctx.fillStyle = "#7c3aed";
  ctx.fillText("crisp text: 11px system-ui", 14, 42);

  // Thin vertical lines (1px), half-pixel aligned
  ctx.strokeStyle = "#7c3aed";
  ctx.lineWidth = 1;
  for (let i = 0; i &lt; 8; i++) {
    const x = alignHalfPixel(20 + i * 12);
    ctx.beginPath();
    ctx.moveTo(x, 56);
    ctx.lineTo(x, 120);
    ctx.stroke();
  }

  // Thin horizontal lines (1px)
  for (let i = 0; i &lt; 4; i++) {
    const y = alignHalfPixel(60 + i * 12);
    ctx.beginPath();
    ctx.moveTo(140, y);
    ctx.lineTo(300, y);
    ctx.stroke();
  }

  // Circle outline
  ctx.beginPath();
  ctx.arc(250, 150, 34, 0, Math.PI * 2);
  ctx.stroke();

  // Pixel-art grid: smoothing disabled, crisp corners
  ctx.imageSmoothingEnabled = false;
  ctx.strokeStyle = "#0ea5e9";
  ctx.strokeRect(alignHalfPixel(20), alignHalfPixel(140), 90, 44);
  for (let gx = 20; gx &lt;= 110; gx += 15) {
    const x = alignHalfPixel(gx);
    ctx.beginPath();
    ctx.moveTo(x, 140);
    ctx.lineTo(x, 184);
    ctx.stroke();
  }
}
</code></pre>
<p>Placing <code>renderHiDPI</code> and <code>renderNaive</code> side by side makes the architectural difference crystal clear:</p>
<pre><code class="language-ts">function renderHiDPI(): void {
  // HiDPI: backing buffer in device pixels, drawing in CSS space -&gt; razor-sharp
  const ctx = setupHiDPICanvas(hidpi, CSS_W, CSS_H, activeDpr);
  drawScene(ctx, "HiDPI: crisp");
}

function renderNaive(): void {
  // Naive: rasterized at 1x CSS resolution, then stretched to device resolution.
  // As dpr increases, upscaling blur becomes more pronounced.
  drawScene(offCtx, "Naive: blurry");
  const { w, h } = deviceSize(CSS_W, CSS_H, activeDpr);
  naive.width = w;
  naive.height = h;
  naive.style.width = `${CSS_W}px`;
  naive.style.height = `${CSS_H}px`;
  const ctx = naive.getContext("2d")!;
  ctx.imageSmoothingEnabled = true; // browser's default bilinear upscaling
  ctx.clearRect(0, 0, w, h);
  ctx.drawImage(offscreen, 0, 0, CSS_W, CSS_H, 0, 0, w, h);
}
</code></pre>
<p>Finally, the HUD and button wiring update the pixel counters live as you switch between <code>1×</code>, <code>2×</code>, and <code>3×</code>:</p>
<pre><code class="language-ts">function updateHud(): void {
  const { w, h } = deviceSize(CSS_W, CSS_H, activeDpr);
  hud.innerHTML =
    `native window.devicePixelRatio: &lt;b&gt;${window.devicePixelRatio}&lt;/b&gt;&lt;br&gt;` +
    `simulated dpr: &lt;b&gt;${activeDpr}×&lt;/b&gt;&lt;br&gt;` +
    `HiDPI backing resolution: &lt;b&gt;${w}×${h}&lt;/b&gt; device pixels&lt;br&gt;` +
    `pixels painted per frame: &lt;b&gt;${(w * h).toLocaleString("en-US")}&lt;/b&gt;&lt;br&gt;` +
    `pixel multiplier pixelRatio(${activeDpr}): &lt;b&gt;${pixelRatio(activeDpr)}×&lt;/b&gt;`;
}

function renderAll(): void {
  renderNaive();
  renderHiDPI();
  updateHud();
}

for (const btn of document.querySelectorAll&lt;HTMLButtonElement&gt;(
  "button[data-dpr]",
)) {
  btn.addEventListener("click", () =&gt; {
    activeDpr = Number(btn.dataset.dpr);
    for (const b of document.querySelectorAll("button[data-dpr]")) {
      b.classList.toggle("active", b === btn);
    }
    renderAll();
  });
}

// Initialize with the display's actual dpr (clamped to 1/2/3 buttons)
activeDpr = Math.min(3, Math.max(1, Math.round(window.devicePixelRatio || 1)));
document
  .querySelector&lt;HTMLButtonElement&gt;(`button[data-dpr="${activeDpr}"]`)
  ?.classList.add("active");

// Re-render automatically if the window is dragged to a different-density monitor
watchDprChange((dpr) =&gt; {
  console.log(`dpr changed to ${dpr}: pixel multiplier ${pixelRatio(dpr)}×`);
  renderAll();
});

renderAll();
</code></pre>
<hr />
<h3>Summary</h3>
<ul>
<li><strong>Two Currencies:</strong> Your screen speaks in <strong>CSS pixels</strong> (layout size) and <strong>device pixels</strong> (physical hardware dots). <code>window.devicePixelRatio</code> is the exchange rate between them.</li>
<li><strong>Bitmap vs. Vector:</strong> Unlike DOM text or SVG, <code>&lt;canvas&gt;</code> is a fixed bitmap. If you don't scale its backing buffer by <code>dpr</code>, the browser stretches it and introduces interpolation blur.</li>
<li><strong>Two Separate Sizes:</strong> Set intrinsic resolution (<code>canvas.width</code> / <code>height</code>) in <strong>device pixels</strong>, and display size (<code>canvas.style.width</code> / <code>height</code>) in <strong>CSS pixels</strong>.</li>
<li><strong>Lock the Rate Once:</strong> Call <code>ctx.scale(dpr, dpr)</code> (or <code>ctx.setTransform(dpr, 0, 0, dpr, 0, 0)</code>) during setup so all downstream drawing code stays cleanly in CSS coordinates.</li>
<li><strong>1px Crisp Lines &amp; Pixel Art:</strong> Offset 1px strokes by <code>+0.5</code> (<code>alignHalfPixel</code>) so they sit inside pixel centers rather than straddling grid boundaries. Set <code>ctx.imageSmoothingEnabled = false</code> for crisp pixel art — and remember to re-apply it after any <code>canvas.width</code> resize.</li>
<li><strong>Dynamic</strong> <code>dpr</code> <strong>Changes:</strong> <code>devicePixelRatio</code> changes when dragging windows across monitors or zooming. Catch transitions with <code>window.matchMedia</code> using a <code>(resolution: 2dppx)</code> media query.</li>
<li><strong>Quadratic</strong> <code>dpr²</code> <strong>Cost:</strong> Sharpness isn't free — fill-rate scales with <code>dpr²</code> (<code>4×</code> at 2x, <code>9×</code> at 3x). On GPU-heavy scenes, clamping with <code>Math.min(dpr, 2)</code> is a smart engineering trade-off.</li>
<li><strong>Measured Reality:</strong> Our <code>npm run bench</code> harness verified the quadratic trend (<code>0.90× -&gt; 3.78× -&gt; 8.40×</code> across <code>dpr</code> 1/2/3).</li>
<li><strong>Test the Math, Not the DOM:</strong> Extract scaling calculations into pure functions with <code>dpr</code> as an argument so your unit tests run fast and deterministically in headless environments.</li>
</ul>
<hr />
<h3>Source Code &amp; Live Demo</h3>
<p>All setup helpers, the <code>matchMedia</code> watcher, the side-by-side comparison demo, the benchmark harness, and the unit test suite are available on GitHub:</p>
<blockquote>
<p>📦 <strong>GitHub Repository:</strong> <a href="https://github.com/m2-md/hidpi-canvas-devicepixelratio">github.com/m2-md/hidpi-canvas-devicepixelratio</a><br />🎮 <strong>Interactive Live Demo:</strong> <a href="https://m2-md.github.io/hidpi-canvas-devicepixelratio/">m2-md.github.io/hidpi-canvas-devicepixelratio</a></p>
</blockquote>
<p>One final thought stayed with me while writing this. Fixing that incomplete <em>"1:1 resolution"</em> sentence from my physics engine article ended up exposing a blurriness in my own old code that I had overlooked for months. Large circles, bold fills, and thick strokes forgive a wrong exchange rate — you don't notice what's missing behind them. But the moment you render a <code>1px</code> grid or <code>11px</code> label on a Retina screen, every bit of accumulated softness jumps right out at you. That's why the best visual test for any Canvas setup is the content hardest on the eyes: thin lines and tiny text. If those are razor-sharp, everything else will be too. 🔍</p>
<hr />
<h3>📚 Canvas 2D &amp; Game Architecture Series</h3>
<ul>
<li><strong>Part 1 (Published):</strong> <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas</a></li>
<li><strong>Part 2 (You are here):</strong> <em>Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes</em></li>
<li><strong>Part 3 (Published):</strong> <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11">Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript</a></li>
<li><strong>Up Next:</strong> <em>Return the Glass, Not the Trash: Object Pools and Zero-Allocation Loops in Canvas</em></li>
</ul>
<h3>👋 About the Author</h3>
<p>I'm <strong>Mustafa Morbel</strong>, a Senior Software Engineer with over 17 years of experience writing about modern web technologies, browser rendering engines, WebGL, and AI development workflows.</p>
<p>You can explore all runnable demos, benchmark harnesses, and test suites on my <a href="https://github.com/mkare">GitHub (@mkare)</a> profile.<br />For new technical guides and architectural deep dives, connect with me on <a href="https://www.linkedin.com/in/mustafamorbel/">LinkedIn</a> and <a href="https://x.com/mustafamorbel">X / Twitter (@mustafamorbel)</a>.</p>
<p>Have you run into tricky Canvas scaling bugs on Retina or multi-monitor setups? I'd love to hear your thoughts and war stories in the comments below 🧠💬</p>
<hr />
<h3>📦 Want the Bundled Starter Kit &amp; Cheatsheets?</h3>
<p>If you want all 3 TypeScript engines, HiDPI helpers, fixed-timestep loop templates, and vector physics cheatsheets in one clean zip, grab the <a href="https://www.buymeacoffee.com/mkare/e/599265"><strong>TS 2D Canvas Physics &amp; HiDPI Starter Kit</strong></a> (or unlock all kits free with a <a href="https://www.buymeacoffee.com/mkare">Buy Me a Coffee membership</a>).</p>
<ul>
<li><strong>Part 1:</strong> <a href="https://m2-md.github.io/canvas-physics-from-scratch/">How Game Physics Works (Canvas Slingshot Engine)</a> · <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8?source=friends_link&amp;sk=f9c8048fe5b2d513b3c0d26127e97fb4">Free Medium Guide</a></li>
<li><strong>Part 2:</strong> <a href="https://m2-md.github.io/hidpi-canvas-devicepixelratio/">Why Canvas Looks Blurry on Retina (devicePixelRatio)</a> · <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8?source=friends_link&amp;sk=3c3af29a65f3d3238efd567f24c20b00">Free Medium Guide</a></li>
<li><strong>Part 3:</strong> <a href="https://m2-md.github.io/fixed-timestep-render-interpolation/">Metronome Physics (Fixed Timestep &amp; Render Interpolation)</a> · <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11?source=friends_link&amp;sk=ff5390a11e2d97b29e82dc41a6572272">Free Medium Guide</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Best Practices for Using TypeScript with React]]></title><description><![CDATA[Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link. ⚡ Get the Production-Ready React Hooks Pack · 📦…]]></description><link>https://mkare.hashnode.dev/best-practices-for-using-typescript-with-react</link><guid isPermaLink="true">https://mkare.hashnode.dev/best-practices-for-using-typescript-with-react</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[react js]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 13:35:03 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Originally published on Medium (JavaScript in Plain English).</em> <a href="https://javascript.plainenglish.io/best-practices-for-using-typescript-with-react-bad13d851143?sk=945cff93536ebbcb01167ee3d48bd979"><em>Read on Medium for free via Friend Link</em></a><em>.</em></p>
<p>⚡ <a href="https://www.buymeacoffee.com/mkare/e/599267"><strong>Get the Production-Ready React Hooks Pack</strong></a> · 📦 <a href="https://github.com/mkare/react-typescript-sample"><strong>Sample Repo on GitHub</strong></a></p>
</blockquote>
<h3>Quick Takeaways</h3>
<ul>
<li><strong>Component &amp; Prop Typing</strong> : Use <code>PropsWithChildren</code>, <code>ComponentProps</code>, <code>Pick</code>, and <code>ComponentType</code> to keep component APIs strict without duplicating type definitions.</li>
<li><strong>Predictable State</strong> : Let <code>useState</code> infer simple primitives, explicitly type nullable or union states, and use discriminated unions with <code>useReducer</code>.</li>
<li><strong>Safe DOM &amp; Component Refs</strong> : Initialize DOM refs with <code>null</code> (<code>useRef&lt;HTMLInputElement | null&gt;(null)</code>) and forward refs cleanly with <code>forwardRef</code>.</li>
<li><strong>Typed Event Handlers</strong> : Rely on React's <code>MouseEventHandler</code> for component events and native <code>Event</code> types for global window listeners.</li>
</ul>
<hr />
<p>Using TypeScript with React can feel daunting at first. However, with the right patterns, the compiler stops feeling like an obstacle and starts acting like a safety net that catches bugs before they hit production. This guide covers practical best practices for integrating TypeScript into React projects, broken into four key sections: components, state management, refs, and events.</p>
<img src="https://cdn-images-1.medium.com/max/800/1*T2NJ61Yx0Q4kqFKzA5nU1g.png" alt="TypeScript and React logos side by side representing type-safe React development" style="display:block;margin:0 auto" />

<p><em>TypeScript and React — building predictable, type-safe UI components at scale.</em></p>
<blockquote>
<p>Learn how to effectively integrate TypeScript with React for better type safety, state management, and event handling. Check out the full implementation on <a href="https://github.com/mkare/react-typescript-sample">GitHub here</a>.</p>
</blockquote>
<h3>Components</h3>
<h4>Defining Basic Props</h4>
<p>React components are typically written as functions that accept a <code>props</code> object. With TypeScript, you define the exact shape of that object so invalid or missing props fail at compile time.</p>
<pre><code class="language-tsx">type BookProps = {
  name: string;
  author?: string; // Optional prop
};

function BookInfo({ name, author }: BookProps) {
  return (
    &lt;div&gt;
      &lt;h2&gt;{name}&lt;/h2&gt;
      {author &amp;&amp; &lt;p&gt;Author: {author}&lt;/p&gt;}
    &lt;/div&gt;
  );
}
</code></pre>
<h4>Handling <code>children</code> Props</h4>
<p>React lets you compose components by passing JSX via <code>children</code>. You can type these props cleanly using React's built-in <code>PropsWithChildren</code> utility.</p>
<pre><code class="language-tsx">import { PropsWithChildren } from 'react';

type CourseProps = {
  courseName: string;
};

function CourseInfo({
  courseName,
  children,
}: PropsWithChildren&lt;CourseProps&gt;) {
  return (
    &lt;div&gt;
      &lt;h1&gt;{courseName}&lt;/h1&gt;
      {children}
    &lt;/div&gt;
  );
}
</code></pre>
<blockquote>
<p><strong>Tip</strong> : If your component only accepts <code>children</code> and no custom props, you can use <code>PropsWithChildren</code> directly without defining an extra type.</p>
</blockquote>
<h4>Passing and Forwarding Props</h4>
<p>Components often need to pass props down to child components. TypeScript's <code>ComponentProps</code> utility extracts a component's prop types directly, keeping types in sync without repetition.</p>
<pre><code class="language-tsx">import { ComponentProps } from 'react';
import BookInfo from './BookInfo';

type BookInfoProps = ComponentProps&lt;typeof BookInfo&gt;;

type Props = {
  themeColor: string;
  title: BookInfoProps['title'];
};

function FeaturedBookInfo({ themeColor, title }: Props) {
  return (
    &lt;div style={{ background: themeColor }}&gt;
      &lt;BookInfo title={title} /&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>If <code>BookInfo</code>'s props change later, TypeScript immediately flags any mismatch in <code>FeaturedBookInfo</code>, reducing maintenance overhead.</p>
<h4>Spreading Props</h4>
<p>Spreading props forwards all props of a wrapper component down to its child. It is especially useful when wrapping existing components with extra styling or behavior without repeating every prop definition.</p>
<pre><code class="language-tsx">import { ComponentProps } from 'react';
import BookInfo from './BookInfo';

type Props = {
  themeColor: string;
} &amp; ComponentProps&lt;typeof BookInfo&gt;;

function HighlightedBookInfo({
  themeColor,
  ...props
}: Props) {
  return (
    &lt;div style={{ background: themeColor }}&gt;
      &lt;BookInfo {...props} /&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>Any updates or new props added to <code>BookInfo</code> automatically propagate to <code>HighlightedBookInfo</code>. If you only want to forward a subset of props, combine <code>ComponentProps</code> with TypeScript's <code>Pick</code> utility:</p>
<pre><code class="language-tsx">import { ComponentProps } from 'react';
import CourseInfo from './CourseInfo';

type CourseInfoProps = ComponentProps&lt;typeof CourseInfo&gt;;

type Props = {
  themeColor: string;
} &amp; Pick&lt;
  CourseInfoProps,
  'courseTitle' | 'courseDuration'
&gt;;

function FeaturedCourseInfo({
  themeColor,
  ...props
}: Props) {
  return (
    &lt;div style={{ background: themeColor }}&gt;
      &lt;CourseInfo {...props} /&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>Here, only <code>courseTitle</code> and <code>courseDuration</code> are exposed and forwarded to <code>CourseInfo</code>.</p>
<h4>Prop Forwarding for HTML Elements</h4>
<p>The same pattern works for native HTML elements. Using <code>ComponentProps&lt;'button'&gt;</code> gives you type-safe access to every valid button attribute, including <code>onClick</code>, <code>disabled</code>, and <code>type</code>.</p>
<pre><code class="language-tsx">import { ComponentProps } from 'react';

type ButtonProps = ComponentProps&lt;'button'&gt;;

function CustomButton(props: ButtonProps) {
  return &lt;button {...props} /&gt;;
}
</code></pre>
<p><code>ComponentProps&lt;'button'&gt;</code> is shorter and more readable than <code>React.JSX.IntrinsicElements['button']</code>. If you ever need to exclude React-specific props like <code>ref</code> or <code>key</code>, you can use <code>React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt;</code> instead.</p>
<h4>Passing JSX (<code>ReactNode</code>)</h4>
<p>Beyond primitive values, you often want to pass raw JSX into named slots—such as a custom sidebar or navigation menu—using <code>ReactNode</code>.</p>
<pre><code class="language-tsx">import { PropsWithChildren, ReactNode } from 'react';

type DashboardProps = {
  title: string;
  menu: ReactNode;
};

function Dashboard({
  title,
  children,
  menu,
}: PropsWithChildren&lt;DashboardProps&gt;) {
  return (
    &lt;div className="dashboard"&gt;
      &lt;aside className="menu"&gt;{menu}&lt;/aside&gt;
      &lt;section className="main-content"&gt;
        &lt;h1&gt;{title}&lt;/h1&gt;
        {children}
      &lt;/section&gt;
    &lt;/div&gt;
  );
}

const menu = (
  &lt;nav&gt;
    &lt;a href="/profile"&gt;Profile&lt;/a&gt;
    &lt;a href="/settings"&gt;Settings&lt;/a&gt;
    &lt;a href="/logout"&gt;Logout&lt;/a&gt;
  &lt;/nav&gt;
);

const App = (
  &lt;Dashboard title="User Dashboard" menu={menu}&gt;
    {/* Dashboard content */}
  &lt;/Dashboard&gt;
);
</code></pre>
<p>Because <code>ReactNode</code> accepts elements, strings, numbers, fragments, and <code>null</code>, it covers every valid renderable value in React.</p>
<h4>Passing Components (<code>ComponentType</code>)</h4>
<p>When you need to pass an entire component as a prop—for example, a custom renderer or dynamic card—use <code>ComponentType&lt;Props&gt;</code>.</p>
<pre><code class="language-tsx">import { ComponentType } from 'react';

type BookDetailProps = {
  title: string;
  genre?: string;
};

type DynamicBookProps = {
  render: ComponentType&lt;BookDetailProps&gt;;
};

function BookDetail({ render: Render }: DynamicBookProps) {
  const props = {
    title: 'Moby Dick',
    genre: 'Adventure',
  };

  return &lt;Render {...props} /&gt;;
}
</code></pre>
<p>This lets the parent pass any component that matches <code>BookDetailProps</code>, giving you flexibility without sacrificing type safety.</p>
<h4>Passing Specific Components Using <code>typeof</code></h4>
<p>When a prop should accept only a specific component (or a structurally identical one), type it with <code>typeof</code>.</p>
<pre><code class="language-tsx">import { ComponentProps } from 'react';
import Icon from './Icon';

type Props = {
  icon?: typeof Icon;
} &amp; ComponentProps&lt;'button'&gt;;

function Button({
  icon: IconComp,
  children,
  ...props
}: Props) {
  return (
    &lt;button {...props}&gt;
      {IconComp &amp;&amp; &lt;IconComp size={24} /&gt;}
      {children}
    &lt;/button&gt;
  );
}
</code></pre>
<p>Using <code>typeof Icon</code> restricts the <code>icon</code> prop to components compatible with <code>Icon</code>'s exact signature.</p>
<h4>Inferring Props with Polymorphic Components</h4>
<p>Component libraries often infer valid props dynamically based on an <code>as</code> prop. For instance, passing <code>as="input"</code> unlocks <code>value</code>, while <code>as="div"</code> rejects it at compile time:</p>
<pre><code class="language-tsx">const App = (
  &lt;&gt;
    {/* Error: div does not have a value prop */}
    &lt;Box as="div" value="foo" /&gt;

    {/* Valid: input supports the value prop */}
    &lt;Box as="input" value="foo" /&gt;
  &lt;/&gt;
);
</code></pre>
<p>By combining <code>ComponentProps</code>, <code>Pick</code>, <code>ReactNode</code>, and <code>ComponentType</code>, you can build flexible, reusable component APIs with minimal boilerplate.</p>
<hr />
<h3>State Management</h3>
<h4>Using <code>useState</code></h4>
<p>TypeScript infers types automatically from simple initial values like numbers or booleans. For nullable values, arrays, or union types, provide the type explicitly via a generic parameter.</p>
<pre><code class="language-tsx">import { useState } from 'react';

type Todo = {
  id: string;
  title: string;
  completed: boolean;
};

function TodoList() {
  const [todos, setTodos] = useState&lt;Todo[] | null&gt;(null);

  return &lt;div&gt;{todos?.length ?? 0} todos&lt;/div&gt;;
}
</code></pre>
<h4>Using <code>useReducer</code></h4>
<p>For state transitions with multiple actions, <code>useReducer</code> paired with a discriminated union for <code>Action</code> ensures every <code>dispatch</code> call is checked against valid payloads.</p>
<pre><code class="language-tsx">import { useReducer } from 'react';

type State = number;
type Action =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'reset'; payload: number };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    case 'reset':
      return action.payload;
    default:
      throw new Error('Unhandled action type');
  }
}

function Counter() {
  const [count, dispatch] = useReducer(reducer, 0);

  return (
    &lt;div&gt;
      &lt;p&gt;Count: {count}&lt;/p&gt;
      &lt;button
        onClick={() =&gt; dispatch({ type: 'increment' })}
      &gt;
        Increment
      &lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<hr />
<h3>Working with Refs</h3>
<p>Refs give you direct access to DOM nodes or imperative component handles. Typing them accurately prevents runtime null-reference errors.</p>
<h4>Creating DOM Refs</h4>
<p>Pass the HTML element type to <code>useRef</code> and initialize it with <code>null</code>, then use optional chaining (<code>?.</code>) when accessing <code>.current</code>.</p>
<pre><code class="language-tsx">import { useRef } from 'react';

function FocusableInput() {
  const inputRef = useRef&lt;HTMLInputElement | null&gt;(null);

  const focusInput = () =&gt; {
    inputRef.current?.focus();
  };

  return (
    &lt;div&gt;
      &lt;input ref={inputRef} type="text" /&gt;
      &lt;button onClick={focusInput}&gt;Focus&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<h4>Forwarding Refs</h4>
<p>When a parent component needs access to a child's underlying DOM element, wrap the child with <code>forwardRef</code> and specify both the element type and props type.</p>
<pre><code class="language-tsx">import { forwardRef } from 'react';

type ButtonProps = {
  label: string;
};

const FancyButton = forwardRef&lt;
  HTMLButtonElement,
  ButtonProps
&gt;(({ label }, ref) =&gt; {
  return &lt;button ref={ref}&gt;{label}&lt;/button&gt;;
});
</code></pre>
<hr />
<h3>Event Handling</h3>
<p>React wraps native browser events in <code>SyntheticEvent</code> types. Using React's built-in handler types guarantees that <code>event.target</code> and <code>event.currentTarget</code> are typed accurately.</p>
<h4>Handling DOM Events</h4>
<p>For component event props, use handler types such as <code>MouseEventHandler&lt;HTMLButtonElement&gt;</code>.</p>
<pre><code class="language-tsx">import { MouseEventHandler } from 'react';

type ButtonProps = {
  onClick: MouseEventHandler&lt;HTMLButtonElement&gt;;
};

function CustomButton({ onClick }: ButtonProps) {
  return &lt;button onClick={onClick}&gt;Click Me&lt;/button&gt;;
}
</code></pre>
<h4>Adding Global Event Listeners</h4>
<p>When attaching listeners directly to <code>window</code> or <code>document</code> inside <code>useEffect</code>, use native DOM <code>Event</code> types rather than React synthetic event types.</p>
<pre><code class="language-tsx">import { useEffect } from 'react';

function ScrollListener() {
  useEffect(() =&gt; {
    const handleScroll = (event: Event) =&gt; {
      console.log('Page scrolled', event.timeStamp);
    };

    window.addEventListener('scroll', handleScroll);
    return () =&gt; {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return &lt;div&gt;Scroll to see console logs.&lt;/div&gt;;
}
</code></pre>
<hr />
<h3>Final Thoughts</h3>
<p>TypeScript and React work best together when you let inference do the heavy lifting and reach for utility types like <code>ComponentProps</code>, <code>PropsWithChildren</code>, and discriminated unions where boundaries matter. Start small, keep your component contracts explicit, and the compiler will pay you back every time you refactor.</p>
<p>Check out the full working examples in the accompanying GitHub repository: <a href="https://github.com/mkare/react-typescript-sample">react-typescript-sample</a>.</p>
<p>Which TypeScript + React pattern saved you the most debugging time in production? I'd love to hear your thoughts 🧠💬</p>
<h3>Keep Exploring</h3>
<ul>
<li><a href="https://medium.com/becoming-for-better/understanding-and-building-react-custom-hooks-a-practical-guide-037ad33d1cd1">Understanding and Building React Custom Hooks — A Practical Guide</a></li>
<li><a href="https://javascript.plainenglish.io/html-native-dialog-component-in-react-with-tailwind-css-2b23356ef036">HTML Native Dialog Component in React with Tailwind CSS</a></li>
<li><a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8">How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas</a></li>
<li><a href="https://www.buymeacoffee.com/mkare/e/599267">React Custom Hooks TypeScript Pack &amp; Cheatsheets (Buy Me a Coffee)</a></li>
</ul>
<hr />
<p><em>Mustafa Morbel is a software engineer with over 17 years of experience building web applications, frontend architectures, and developer tools.</em></p>
]]></content:encoded></item><item><title><![CDATA[How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas]]></title><description><![CDATA[🎮 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…]]></description><link>https://mkare.hashnode.dev/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas</link><guid isPermaLink="true">https://mkare.hashnode.dev/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[canvas]]></category><dc:creator><![CDATA[Mustafa Morbel]]></dc:creator><pubDate>Thu, 19 Nov 2026 13:32:10 GMT</pubDate><content:encoded><![CDATA[<h3><em>Originally published on Medium (JavaScript in Plain English).</em> <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8?source=friends_link&amp;sk=f9c8048fe5b2d513b3c0d26127e97fb4"><em>Read on Medium for free via Friend Link</em></a><em>.</em></h3>
<p>🎮 <a href="https://m2-md.github.io/canvas-physics-from-scratch/"><strong>Try the Live Interactive Demo</strong></a> · 📦 <a href="https://github.com/m2-md/canvas-physics-from-scratch"><strong>GitHub Repo &amp; Vitest Suite</strong></a> · ⚡ <a href="https://www.buymeacoffee.com/mkare/e/599265"><strong>Get the TS 2D Canvas Physics Starter Kit</strong></a></p>
<img src="https://raw.githubusercontent.com/m2-md/canvas-physics-from-scratch/main/assets/demo.gif" alt="Interactive Demo Preview" style="display:block;margin:0 auto" />

<img src="https://miro.medium.com/v2/resize:fit:1400/1*Asr_KUtIdWekULYCr9UWTg.png" alt="Architecture overview of a custom 2D physics engine in HTML5 Canvas showing gravity, collision normals, and impulse vectors" style="display:block;margin:0 auto" />

<p><em>Under the hood of 2D game physics: vector integration, collision normals, and impulse resolution in HTML5 Canvas.</em></p>
<h3>What We Build Under the Hood</h3>
<ul>
<li><strong>Semi-Implicit Euler Gravity:</strong> Two lines of <code>dt</code>-scaled vector integration that turn static coordinates into falling bodies.</li>
<li><strong>Inverse Mass (</strong><code>1 / m = 0</code><strong>):</strong> Modeling immovable walls and dynamic projectiles through one branch-free formula.</li>
<li><strong>Impulse &amp; Positional Correction:</strong> Resolving circle-to-circle collisions along surface normals without floor jitter.</li>
<li><strong>Matter.js Production Trade-offs:</strong> Porting our ~145-line custom solver to Matter.js to expose tunneling and engine boundaries.</li>
</ul>
<hr />
<p>A few weeks ago, I was reading a game development tutorial. It cheerfully announced: <em>"Physics sounds intimidating... but don't worry, a physics engine will handle all the math for you!"</em> 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.</p>
<p>That sentence genuinely bothered me.</p>
<p>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.</p>
<p>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.</p>
<p>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: <em>when should you build your own, and when should you use an established library?</em></p>
<p>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.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*z8YgP1xAC-fpxHHoTJxpzA.png" alt="Diagram of the browser requestAnimationFrame game loop measuring delta time, stepping physics, and rendering to 2D Canvas" style="display:block;margin:0 auto" />

<p><em>The three-phase browser game loop: measure delta time (dt), step the physics world, and redraw the 2D Canvas frame.</em></p>
<h3>Setting the Stage: The Game Loop</h3>
<p>At the heart of every game beats a steady pulse: the <strong>game loop</strong>. Roughly 60 times every second, it executes three distinct steps:</p>
<ol>
<li><strong>Measure time</strong> (how many seconds elapsed since the previous frame?)</li>
<li><strong>Update the world</strong> (physics calculations live here)</li>
<li><strong>Render to screen</strong> (clearing and redrawing the Canvas)</li>
</ol>
<p>In the browser, we build this loop around <code>requestAnimationFrame</code>. Much like the browser's event loop, <code>requestAnimationFrame</code> hooks directly into the browser's display refresh cycle, invoking our callback right before the screen paints:</p>
<pre><code class="language-ts">// 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);
</code></pre>
<p>The variable <code>dt</code> stands for <strong>delta time</strong> — 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 <em>"move 5 pixels per frame"</em>, your game will run twice as fast on high-refresh hardware. But if you state <em>"travel 300 pixels per second, moving</em> <code>300 * dt</code> <em>each frame"</em>, the simulation moves at the exact same physical speed across any device.</p>
<p>Notice the <code>Math.min(..., 1 / 30)</code> cap. If a player switches browser tabs for five seconds and returns, an uncapped <code>dt</code> 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 <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11">Part 3: Metronome Physics — Fixed Timestep Game Loops and Render Interpolation in TypeScript</a>, we upgrade this variable <code>dt</code> step into a deterministic fixed-timestep accumulator loop across 60Hz and 144Hz monitors.</p>
<hr />
<h3>Vectors: The Alphabet of Physics</h3>
<p>In a 2D coordinate space, almost every physical concept boils down to two numbers: <code>x</code> and <code>y</code>. 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:</p>
<pre><code class="language-ts">// src/engine/vec.ts
export type Vec2 = { x: number; y: number };

export const vec = (x = 0, y = 0): Vec2 =&gt; ({ x, y });
export const add = (a: Vec2, b: Vec2): Vec2 =&gt; vec(a.x + b.x, a.y + b.y);
export const sub = (a: Vec2, b: Vec2): Vec2 =&gt; vec(a.x - b.x, a.y - b.y);
export const scale = (a: Vec2, s: number): Vec2 =&gt; vec(a.x * s, a.y * s);
export const length = (a: Vec2): number =&gt; Math.hypot(a.x, a.y);
export const dot = (a: Vec2, b: Vec2): number =&gt; a.x * b.x + a.y * b.y;
export const normalize = (a: Vec2): Vec2 =&gt; {
  const len = length(a);
  return len === 0 ? vec() : scale(a, 1 / len);
};
</code></pre>
<p>Two functions in this module are our star players:</p>
<ul>
<li><code>normalize</code><strong>:</strong> Strips away a vector's magnitude and preserves only its direction (reducing its length to 1). This answers: <em>"In which direction did the collision occur?"</em></li>
<li><code>dot</code> <strong>(Dot Product):</strong> Measures the projection (the "shadow") of one vector onto another. This answers: <em>"How much of the ball's velocity is heading directly perpendicular into the surface?"</em></li>
</ul>
<p>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.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*9zGhlUpAJ3esv8AWJLpDfA.png" alt="2D circle rigid body properties showing position, velocity vector, radius, bounciness, and inverse mass for static walls" style="display:block;margin:0 auto" />

<p><em>Modeling dynamic circles and immovable static obstacles with a single Body structure using inverse mass (invMass = 0).</em></p>
<h3>Bodies: The Actors in Our World</h3>
<p>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.</p>
<pre><code class="language-ts">// 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,
  };
}
</code></pre>
<p>Notice the seemingly unusual property: instead of storing <code>mass</code>, we store <code>invMass</code> (inverse mass, <code>1 / mass</code>). Why?</p>
<p>In physics engines, non-moving boundaries — walls, floors, pillars — are modeled as objects of infinite mass. In code, multiplying or dividing by <code>Infinity</code> leads to edge-case headaches and <code>NaN</code> values. But if you store inverse mass, an infinite mass turns cleanly into <code>0</code>:</p>
<blockquote>
<p><strong>1 / ∞ = 0</strong></p>
</blockquote>
<p>During collision resolution, <code>invMass</code> 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.</p>
<p>Additionally, setting <code>1 / (radius * radius)</code> 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.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*pwvQ8juX4y-yXvX6XIWXmA.png" alt="Semi-implicit Euler integration diagram illustrating downward gravity acceleration updating velocity and y-axis position" style="display:block;margin:0 auto" />

<p><em>Semi-implicit Euler integration over discrete time steps: gravity accelerates velocity, and velocity advances position.</em></p>
<h3>Gravity: A Two-Line Universe</h3>
<p>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:</p>
<pre><code class="language-ts">// 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
</code></pre>
<p>Two lines. That's it.</p>
<p>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 <strong>Euler integration</strong> — 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.</p>
<p>Here is how our <code>World</code> class starts coming together:</p>
<pre><code class="language-ts">// 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 -&gt; velocity -&gt; 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 &lt; this.bodies.length; i++) {
      for (let j = i + 1; j &lt; this.bodies.length; j++) {
        this.collideBodies(this.bodies[i], this.bodies[j]);
      }
    }
  }
}
</code></pre>
<p>Notice the default <code>gravityY = 900</code>. 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 — <em>Angry Birds</em> doesn't simulate real planetary gravitation, it simulates what feels good under your thumb.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*Z1KIOQKOOhTZujZHpVOcDw.png" alt="Canvas boundary collision resolution snapping overlapping circle position inside wall bounds before reflecting velocity" style="display:block;margin:0 auto" />

<p><em>Wall collision response: clamp overlapping geometry back inside the viewport first, then invert and dampen normal velocity.</em></p>
<h3>Screen Boundaries: Our First Collision</h3>
<p>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:</p>
<pre><code class="language-ts">// src/engine/world.ts — World body method
private collideWalls(b: Body) {
  if (b.invMass === 0) return;

  if (b.pos.x - b.radius &lt; 0) {
    b.pos.x = b.radius;
    b.vel.x = -b.vel.x * b.bounciness;
  }
  if (b.pos.x + b.radius &gt; this.width) {
    b.pos.x = this.width - b.radius;
    b.vel.x = -b.vel.x * b.bounciness;
  }
  if (b.pos.y - b.radius &lt; 0) {
    b.pos.y = b.radius;
    b.vel.y = -b.vel.y * b.bounciness;
  }
  if (b.pos.y + b.radius &gt; this.height) {
    b.pos.y = this.height - b.radius;
    b.vel.y = -b.vel.y * b.bounciness;
  }
}
</code></pre>
<p>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 <code>bounciness</code>. A <code>bounciness</code> value of <code>0.6</code> retains 60% of the normal velocity upon impact — gradually dissipating kinetic energy like a real basketball.</p>
<p>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.</p>
<p>The golden rule of game physics: <strong>always resolve geometry before resolving velocity.</strong></p>
<hr />
<h3>Body-to-Body Collisions: Impulse Resolution</h3>
<p>Now comes the centerpiece. Resolving a collision between two moving circles breaks down into two questions: <em>did they collide?</em> and <em>what happens next?</em></p>
<p>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 <strong>impulse</strong> (instantaneous force applied over time):</p>
<pre><code class="language-ts">// 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 &gt;= 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 &gt; 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)));
}
</code></pre>
<p>Let's unpack these twenty lines, because they constitute the mathematical core of nearly every modern 2D physics engine:</p>
<ul>
<li><code>normal</code><strong>:</strong> The unit vector pointing from the center of body <code>a</code> to body <code>b</code>. It defines the axis along which momentum must transfer.</li>
<li><code>approach</code><strong>:</strong> 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.</li>
<li><code>impulse</code><strong>:</strong> The scalar magnitude of the collision force. The factor <code>(1 + e)</code> incorporates the restitution (elasticity) of the bounce. Dividing by <code>totalInvMass</code> distributes the reaction force according to each body's weight. A massive body (<code>small invMass</code>) barely budges; a light body (<code>large invMass</code>) gets flung across the screen; and an immovable static body (<code>invMass = 0</code>) stays locked in space. One clean formula, three distinct physical behaviors.</li>
<li><strong>Positional Correction:</strong> Just like the floor collision, we push overlapping circles apart immediately along the normal vector, proportional to their inverse mass.</li>
<li><code>emitContact</code><strong>:</strong> The physics engine's boundary hook to the outside world. It publishes an event stating: <em>"These two bodies collided with this exact impact speed."</em></li>
</ul>
<p>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.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*nW6gJHrSEZ13Ft4W4SBMgw.png" alt="Slingshot launch mechanic diagram showing pointer drag vector pulling backward and opposite initial velocity vector" style="display:block;margin:0 auto" />

<p><em>Slingshot launch geometry: dragging backward from the anchor computes an opposite launch velocity scaled by pull distance.</em></p>
<h3>The Slingshot: Impulse Under Your Fingertip</h3>
<p>Our simulation is functional. Now we turn it into a game: grab the projectile, drag backwards, and release. The core mechanic that powered <em>Angry Birds</em>.</p>
<p>The concept is straightforward: applying velocity in the exact opposite direction of the drag vector. The farther you pull, the faster the projectile launches:</p>
<pre><code class="language-ts">// src/main.ts
canvas.addEventListener("pointerdown", (e) =&gt; {
  const p = toWorld(e);
  if (length(sub(p, ball.pos)) &lt; 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) =&gt; {
  if (dragging) dragPoint = toWorld(e);
});

window.addEventListener("pointerup", () =&gt; {
  if (!dragging) return;
  dragging = false;
  const pull = sub(ball.pos, dragPoint); // Opposite of drag = launch vector
  ball.vel = scale(pull, LAUNCH_POWER);
});
</code></pre>
<p>That comment about <code>window</code> listeners comes from a real bug I hit while testing: registering <code>pointerup</code> strictly on the <code>&lt;canvas&gt;</code> 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: <strong>bind initiation to the element, but bind drag updates and release to</strong> <code>window</code><strong>.</strong></p>
<p>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.</p>
<hr />
<img src="https://miro.medium.com/v2/resize:fit:1400/1*h_qq7bM-R7z7Txcn2zeHFA.png" alt="Playable HTML5 Canvas slingshot rescue game showing projectile aiming at stone ring protecting the central target orb" style="display:block;margin:0 auto" />

<p><em>The finished Rescue Operation mini-game in HTML5 Canvas: shatter high-threshold stone blocks to free the central pink orb.</em></p>
<h3>The Game: Rescue Operation</h3>
<p>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.</p>
<p>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?</p>
<p>Setup takes only a few lines. To ensure consistent behavior across different screen sizes, we normalize all dimensions against the viewport's shorter dimension:</p>
<pre><code class="language-ts">// 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&lt;Body&gt;();
const STONES = 10;
for (let i = 0; i &lt; 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);
}
</code></pre>
<p>Notice <code>900 * SCALE</code>. 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 <code>window.innerWidth</code> Canvas coordinates razor-sharp on HiDPI screens without distorting physics space, check out <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8">Part 2: Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes</a>.</p>
<p>And the gameplay rules live cleanly inside our contact listener:</p>
<pre><code class="language-ts">// src/main.ts — gameplay mechanics
const BREAK_SPEED = 400 * SCALE; // px/s — slower impacts won't shatter stones

world.onContact(({ a, b, speed }) =&gt; {
  const other = a === ball ? b : b === ball ? a : null;
  if (!other) return;

  if (stones.has(other) &amp;&amp; speed &gt; BREAK_SPEED) {
    world.remove(other);
    stones.delete(other);
    spawnParticles(other.pos);
  }

  if (other === pink) {
    world.remove(pink);
    won = true; // RESCUED!
  }
});
</code></pre>
<p>The <code>speed</code> 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.</p>
<p>The entire physics engine is ~145 lines. The game logic is ~210 lines. And every single bounce on the screen is fully transparent.</p>
<hr />
<h3>What About Production? Returning to Matter.js</h3>
<p>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?</p>
<p>No.</p>
<p>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.</p>
<p>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:</p>
<pre><code class="language-ts">// 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) =&gt; {
  for (const pair of event.pairs) {
    // pair.collision.normal -&gt; our "normal"
    // pair.collision.depth  -&gt; our "overlap"
  }
});
</code></pre>
<p>Look familiar?</p>
<p><code>restitution</code> is our <code>bounciness</code>, <code>isStatic</code> is our <code>invMass = 0</code>, and <code>collisionStart</code> is our <code>onContact</code>. The terminology changed; the underlying physics concepts are identical. The black box is now made of clear glass.</p>
<p>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 <strong>tunneling</strong>: a high-speed body moves past the boundary in a single frame, so a discrete collision test never detects an intersection.</p>
<p>In our custom engine, walls were handled as strict geometric boundaries (<code>pos.x = radius</code>), 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.</p>
<h3>Architecture Decision Matrix</h3>
<ul>
<li><strong>Custom Micro-Engine:</strong> Educational experiments, hyper-targeted mini-games with simple mechanics (bouncing balls, breakout clones), or ultra-lightweight web widgets where zero bundle footprint is mandatory.</li>
<li><strong>Matter.js:</strong> Polygons, rotation, stacking boxes, springs, constraints, and fast prototyping for production 2D web games.</li>
<li><strong>Box2D / Rapier (WASM):</strong> Performance-critical simulations, high object counts, or authoritative game servers requiring deterministic physics across platforms.</li>
</ul>
<hr />
<h3>Summary</h3>
<ul>
<li><strong>Game Loop:</strong> Drive simulation with <code>requestAnimationFrame</code> and <code>dt</code>; define all speeds per second, never per frame.</li>
<li><strong>Euler Integration:</strong> Gravity is two lines: <code>velocity += gravity * dt</code> and <code>position += velocity * dt</code>.</li>
<li><strong>Inverse Mass:</strong> Store <code>1 / mass</code> so static, immovable obstacles cost zero conditional branches in your solver.</li>
<li><strong>Two-Step Collision:</strong> First detect overlap (<code>dist &lt; r1 + r2</code>), then calculate the impulse response along the collision normal.</li>
<li><strong>Geometry First, Velocity Second:</strong> Always resolve physical intersection before adjusting velocities to prevent jittering.</li>
<li><strong>Decoupled Architecture:</strong> Game logic belongs in contact events, never inside the physics integration loop.</li>
<li><strong>Pragmatic Production:</strong> Understand the mechanics by building it once, then use battle-tested libraries like Matter.js or Rapier in production.</li>
</ul>
<hr />
<h3>📚 Canvas 2D &amp; Game Architecture Series</h3>
<blockquote>
<p>🗺️ <strong>Series Roadmap:</strong> Follow the full browser rendering and physics architecture arc from vector math to deterministic loops.</p>
</blockquote>
<ul>
<li><strong>Part 1 (You are here):</strong> <strong>How Game Physics Works: Building a 2D Physics Engine from Scratch in Canvas</strong></li>
<li><strong>Part 2:</strong> <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8"><strong>Why Does Canvas Look Blurry on Retina Displays? devicePixelRatio and the Tale of Two Sizes</strong></a> — Solving HiDPI rendering blurriness without distorting physics coordinates.</li>
<li><strong>Part 3:</strong> <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11"><strong>Metronome Physics: Fixed Timestep Game Loops and Render Interpolation in TypeScript</strong></a> — Taming variable delta time to make simulation physics completely deterministic across 60Hz and 144Hz monitors.</li>
<li><strong>Up Next:</strong> <strong>Broad-Phase Collision &amp; Spatial Hashing (O(n²) -&gt; O(n))</strong> — Scaling collision detection from 200 to 20,000 objects with spatial grid partitioning.</li>
</ul>
<hr />
<h3>Source Code &amp; Playable Demo</h3>
<p>The complete source code — including the custom engine, playable game, automated tests, and Matter.js comparison — is open-source on GitHub:</p>
<blockquote>
<p>📦 <strong>GitHub Repository:</strong> <a href="https://github.com/m2-md/canvas-physics-from-scratch">github.com/m2-md/canvas-physics-from-scratch</a><br />🎮 <strong>Playable Live Demo:</strong> <a href="https://m2-md.github.io/canvas-physics-from-scratch/">m2-md.github.io/canvas-physics-from-scratch</a></p>
</blockquote>
<p>Building this project reminded me of an interesting reality: much of the intimidation surrounding the term <em>"physics engine"</em> 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.</p>
<p>Pull back the slingshot and smash the stones. The pink orb is waiting. ⚙️🧠</p>
<hr />
<h3>👋 About the Author</h3>
<p>I'm <strong>Mustafa Morbel</strong>, a senior software engineer and architect with over 17 years of experience building scalable web applications, interactive browser graphics, and AI-assisted engineering workflows.</p>
<p>You can inspect all codebases, runnable demos, and test suites across my <a href="https://github.com/mkare">GitHub profile</a>.<br />For new technical guides and architectural deep dives, feel free to connect on <a href="https://www.linkedin.com/in/mustafamorbel/">LinkedIn</a> and <a href="https://x.com/mustafamorbel">X / Twitter (@mustafamorbel)</a>.</p>
<p>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 🧠💬</p>
<hr />
<h3>📦 Want the Bundled Starter Kit &amp; Cheatsheets?</h3>
<p>If you want all 3 TypeScript engines, HiDPI helpers, fixed-timestep loop templates, and vector physics cheatsheets in one clean zip, grab the <a href="https://www.buymeacoffee.com/mkare/e/599265"><strong>TS 2D Canvas Physics &amp; HiDPI Starter Kit</strong></a> (or unlock all kits free with a <a href="https://www.buymeacoffee.com/mkare">Buy Me a Coffee membership</a>).</p>
<ul>
<li><strong>Part 1:</strong> <a href="https://m2-md.github.io/canvas-physics-from-scratch/">How Game Physics Works (Canvas Slingshot Engine)</a> · <a href="https://javascript.plainenglish.io/how-game-physics-works-building-a-2d-physics-engine-from-scratch-in-canvas-5cd26416ddb8?source=friends_link&amp;sk=f9c8048fe5b2d513b3c0d26127e97fb4">Free Medium Guide</a></li>
<li><strong>Part 2:</strong> <a href="https://m2-md.github.io/hidpi-canvas-devicepixelratio/">Why Canvas Looks Blurry on Retina (devicePixelRatio)</a> · <a href="https://javascript.plainenglish.io/why-does-canvas-look-blurry-on-retina-displays-devicepixelratio-and-the-tale-of-two-sizes-2be8f6e6f7f8?source=friends_link&amp;sk=3c3af29a65f3d3238efd567f24c20b00">Free Medium Guide</a></li>
<li><strong>Part 3:</strong> <a href="https://m2-md.github.io/fixed-timestep-render-interpolation/">Metronome Physics (Fixed Timestep &amp; Render Interpolation)</a> · <a href="https://javascript.plainenglish.io/metronome-physics-fixed-timestep-game-loops-and-render-interpolation-in-typescript-cdf54ec5ea11?source=friends_link&amp;sk=ff5390a11e2d97b29e82dc41a6572272">Free Medium Guide</a></li>
</ul>
]]></content:encoded></item></channel></rss>