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 Canvas Physics Starter Kit
Try the Interactive Live Demo · Full TypeScript Source & Tests on GitHub
Quick takeaways
- 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.
- A ratio-based merge rule snowballs and inflates dirty area by a third; a fixed
maxWastepixel budget (2,000 px²) cuts clip regions by 40% while keeping dirty area at 12.5%. - Above 5% moving objects,
DirtyTrackerautomatically falls back to a full redraw (0.015 msoverhead) instead of burning44 msmerging rectangles. - 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.
Every canvas demo I have built in this series starts its draw function with the exact same reflex: wiping the entire canvas clean.
// 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); It was there in the 2D physics engine and the Part 4 object pool demo (painting over with fillRect), and it stayed unchanged in the HiDPI Retina canvas and the fixed timestep loop. It becomes muscle memory: start the frame, wipe everything, redraw everything. Nobody questions it because it works.
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.
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.
We can break that reflex and wipe only the spots that actually got dirty.
Wiping everything every frame
Putting a number on the bill makes the wasted work concrete.
A typical Canvas 2D frame pays two costs. The first is pixel cost: clearRect and every fillRect or drawImage 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 devicePixelRatio = 2, that jumps fourfold.
The second is call cost: the save, translate, beginPath, fill, and restore calls issued for every object. Canvas 2D pays a fixed overhead per draw call, and it scales linearly with object count.
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.
Canvas 2D gives us a guarantee we rarely cash in on: unless you call clearRect, 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.
The dirty region idea
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.
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.
First, we need a rectangle type and pure geometry helpers. This entire file is 100% testable and never touches the DOM:
// 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 < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < 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 > 0 && h > 0 ? w * h : 0; } 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.
The fix is a single step. Inflate every dirty rectangle by one pixel, then snap it outward to integer coordinates:
// 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) }; } If you use shadowBlur or a thick lineWidth, 1 pixel will not be enough; set pad to the radius of your effect. The rule is simple: pad must be at least the farthest distance a stroke or shadow can bleed past the geometric bounding box.
Collecting dirty rectangles
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.
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.
That is why DirtyTracker starts with markMoved:
// 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) > 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 > this.maxRegions * 4) return [{ ...this.bounds }]; const merged = mergeRects(this.rects, this.maxWaste); // Too fragmented? A single full redraw is cheaper. if (merged.length > 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) => ({ ...r })); } } 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 dirty flag and calling markRect(obj.bounds) when it is raised keeps everything clean: markMoved handles motion, and markRect handles appearance.
markAll() is your escape hatch. Window resized, theme switched, scene reloaded: everything is dirty, no argument needed.
That first guard inside regions() came directly from profiling. The merger scans pairs (O(n²)), 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 maxRegions dropped that exact scenario to 0.029 ms. (You will not see that 44 ms in npm run bench; I measured it manually with simulate(2000, 200, { maxRegions: 1000 }), while 0.029 ms is the default config shown in the final decision table.) Always measure the cost of an optimization itself.
To merge or to draw separately
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 save/clip/restore tax; a hundred tiny regions can cost more than one medium-sized region.
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.
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.
// 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) => ({ ...r })); let changed = true; while (changed) { changed = false; let bi = -1; let bj = -1; let best = Infinity; for (let i = 0; i < out.length; i++) { for (let j = i + 1; j < 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 <= maxWaste && waste < best) { best = waste; bi = i; bj = j; } } if (best === -1) break; } if (bi >= 0) { out[bi] = rectUnion(out[bi], out[bj]); out.splice(bj, 1); changed = true; } } return out; } 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.
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:
// src/merge.ts (initial version kept for benchmark comparison) export function mergeRectsRatio(rects: Rect[], maxGrowth = 1.5): Rect[] { const out: Rect[] = rects.map((r) => ({ ...r })); let changed = true; while (changed) { changed = false; outer: for (let i = 0; i < out.length; i++) { for (let j = i + 1; j < out.length; j++) { const union = rectUnion(out[i], out[j]); // Snowball effect: as the merged rect grows, this threshold grows too. if ( rectArea(union) <= maxGrowth * Source:https://dev.to/mkare/no-need-to-wipe-the-whole-table-dirty-rectangle-rendering-in-canvas-2d-4587 Related posts

Debounce vs. Throttle in JavaScript: The Difference, With Code

Shaking Hands with Everyone: Broad-Phase Collision and Spatial Hashing from 200 to 20,000 Bodies

Quita tus 3 mejores trades: la prueba de 5 minutos que desarma un backtest

