When teams start building an interactive floor-plan editor, diagramming canvas, or architectural CAD viewport in the browser, the default instinct is to pull in Fabric.js, Konva, or PixiJS.
For general-purpose drawing boards, a retained-mode scene graph makes sense. For an architectural CAD studio where every wall has a physical thickness in inches, doors live along wall centerlines, rooms are solved dynamically from a planar graph, and dragging one wall slides an entire collinear chain, a generic canvas scene graph quickly becomes a second source of truth you spend half your week fighting.
In PlanCaliber, our 2D CAD editor runs directly on a single HTML5 <canvas> element in pure TypeScript with zero canvas dependencies. All state lives in world inches (1 ft = 12 in), and rendering is a pure function of (solvedPlan, panX, panY, zoom, selection).
Here are the four core interaction primitives that make a raw HTML5 <canvas> feel like native desktop CAD.
1. World-to-Screen Math & Cursor-Anchored Zoom
Every wall vertex, opening offset, and fixture coordinate stays in world inches (+x East, +y South). The camera is just three numbers: panX, panY (in CSS pixels), and zoom (screen pixels per world inch).
interface Point2D { x: number; y: number; } function worldToScreen(wx: number, wy: number, panX: number, panY: number, zoom: number): Point2D { return { x: panX + wx * zoom, y: panY + wy * zoom }; } function screenToWorld(sx: number, sy: number, panX: number, panY: number, zoom: number): Point2D { return { x: (sx - panX) / zoom, y: (sy - panY) / zoom }; } When a user scrolls the wheel or pinches on a trackpad, the single most important invariant is cursor-anchored zoom: the exact world inch under (cx, cy) before zooming must remain under (cx, cy) after zooming.
function zoomAroundScreenPoint( factor: number, cx: number, cy: number, state: { panX: number; panY: number; zoom: number } ) { const before = screenToWorld(cx, cy, state.panX, state.panY, state.zoom); const nextZoom = Math.max(0.2, Math.min(10, state.zoom * factor)); state.zoom = nextZoom; state.panX = cx - before.x * nextZoom; state.panY = cy - before.y * nextZoom; } Notice we never accumulate rounding error inside panX/panY — each step solves cx = panX + before.x * nextZoom directly. Combined with a ResizeObserver on the canvas wrapper and window.devicePixelRatio backing-store scaling, lines stay crisp at both 0.25 px/in whole-house view and 8.0 px/in cabinet-clearance zoom.
2. Zoom-Aware Snapping: Ortho-First Angle Lock + T-Junction Wall Capture
Raw pixel grids feel terrible in residential drafting. When a user draws a partition wall, they want a strict priority hierarchy:
- Existing corner capture (
Math.max(13 / zoom, 7)inches): screen-constant pixel magnet so you can close a room reliably whether zoomed out or zoomed in. - Architectural ortho-first angle lock: strongly prefer
90°(±26°capture window) with a lighter45°detent (±7°), snapping wall length to1/2"increments unlessShiftunlocks free angle. - Cross-plan guide alignment: snap
xoryto existing vertices within4"so opposite walls align effortlessly across hallways. - T-junction centerline snap: project the candidate point onto every existing wall segment (
t ∈ (0.02, 0.98)) so interior partitions terminate cleanly on an existing wall centerline instead of stopping 2 inches short and breaking room closure.
function distPointToSegment( px: number, py: number, ax: number, ay: number, bx: number, by: number ): { dist: number; t: number; projX: number; projY: number } { const dx = bx - ax; const dy = by - ay; const lenSq = dx * dx + dy * dy; if (lenSq < 1e-6) { return { dist: Math.hypot(px - ax, py - ay), t: 0, projX: ax, projY: ay }; } const t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / lenSq)); const projX = ax + t * dx; const projY = ay + t * dy; return { dist: Math.hypot(px - projX, py - projY), t, projX, projY }; } function snapVertexPoint( wx: number, wy: number, zoom: number, vertices: { id: string; x: number; y: number }[], walls: { id: string; startId: string; endId: string; start: Point2D; end: Point2D }[], excludeVertexId?: string, anchorOther?: Point2D | null, freeAngle = false ): { x: number; y: number; snappedVertexId?: string; snappedWallId?: string } { // 1. Existing vertex magnet (constant ~13px screen radius, floor 7") const snapRadiusIn = Math.max(13 / zoom, 7); for (const v of vertices) { if (v.id === excludeVertexId) continue; if (Math.hypot(wx - v.x, wy - v.y) <= snapRadiusIn) { return { x: v.x, y: v.y, snappedVertexId: v.id }; } } let sx = Math.round(wx); let sy = Math.round(wy); // 2. Ortho-first 90 deg / 45 deg polar snap from anchor vertex if (anchorOther && !freeAngle) { const dx = wx - anchorOther.x; const dy = wy - anchorOther.y; const len = Math.hypot(dx, dy); if (len > 3) { const deg = (Math.atan2(dy, dx) * 180) / Math.PI; const orthoDeg = Math.round(deg / 90) * 90; const diagDeg = Math.round(deg / 45) * 45; const snappedLen = Math.round(len * 2) / 2; if (Math.abs(deg - orthoDeg) <= 26) { const rad = (orthoDeg * Math.PI) / 180; sx = anchorOther.x + Math.cos(rad) * snappedLen; sy = anchorOther.y + Math.sin(rad) * snappedLen; } else if (Math.abs(deg - diagDeg) <= 7) { const rad = (diagDeg * Math.PI) / 180; sx = anchorOther.x + Math.cos(rad) * snappedLen; sy = anchorOther.y + Math.sin(rad) * snappedLen; } } } // 3. Cross-plan alignment to existing vertex axes for (const v of vertices) { if (v.id === excludeVertexId) continue; if (Math.abs(sx - v.x) <= 4) sx = v.x; if (Math.abs(sy - v.y) <= 4) sy = v.y; } // 4. T-junction snap onto an existing wall centerline const wallSnapTol = Math.max(14 / zoom, 9); let bestWall: { x: number; y: number; wallId: string; dist: number } | null = null; for (const sw of walls) { if (excludeVertexId && (sw.startId === excludeVertexId || sw.endId === excludeVertexId)) { continue; } const hit = distPointToSegment(sx, sy, sw.start.x, sw.start.y, sw.end.x, sw.end.y); if (hit.t > 0.02 && hit.t < 0.98 && hit.dist <= wallSnapTol) { if (!bestWall || hit.dist < bestWall.dist) { bestWall = { x: hit.projX, y: hit.projY, wallId: sw.id, dist: hit.dist }; } } } if (bestWall) { return { x: Math.round(bestWall.x * 4) / 4, y: Math.round(bestWall.y * 4) / 4, snappedWallId: bestWall.wallId }; } return { x: Math.round(sx * 4) / 4, y: Math.round(sy * 4) / 4 }; } Quantizing every returned coordinate to 1/4" (Math.round(v * 4) / 4) aligns the interactive canvas directly with our imperial dimension formatter and planar-graph room healer.
3. Priority-Layered World Hit-Testing (Including Rotated Fixtures & Openings)
Without a retained DOM or scene-graph hit buffer, clicking the canvas calls a deterministic hitTestWorld(wx, wy) function in strict architectural Z-order:
- Electrical symbols (small targets on walls/ceilings — highest priority so outlets never get trapped behind cabinets)
- Doors & windows (tested in each wall's rotated local frame)
- Cabinets & furniture fixtures (rotated bounding boxes)
- Walls (point-to-segment distance
<= wall.thicknessIn / 2 + tolIn) - Enclosed rooms (ray-casting point-in-polygon fallback)
Checking rotated doors, angled islands, and furniture takes 8 lines by rotating the pointer into the object's local coordinate frame:
function pointInRotatedBox( px: number, py: number, cx: number, cy: number, w: number, d: number, rotDeg: number, padIn = 2 ): boolean { const rad = (-rotDeg * Math.PI) / 180; const cos = Math.cos(rad); const sin = Math.sin(rad); const dx = px - cx; const dy = py - cy; const lx = dx * cos - dy * sin; const ly = dx * sin + dy * cos; return Math.abs(lx) <= w / 2 + padIn && Math.abs(ly) <= d / 2 + padIn; } For a residential floor plan (30–120 walls, 15–60 fixtures), a linear priority pass runs in under 0.05 milliseconds per pointer move — fast enough for live hover highlights without maintaining an R-tree or duplicate hit-canvas. And when the user activates the 1-Wall Calibrate tool, hitTestWorld short-circuits immediately to walls only so clicking a wall behind a countertop never accidentally selects the cabinet.
4. Typing Every Drag Gesture as a Discriminated Union
Canvas interaction bugs almost always come from tangled boolean flags (isDragging, isPanning, draggingWall, draggingVertex). Replacing those booleans with a single discriminated union makes illegal states unrepresentable:
type DragState = | { kind: 'pan'; startScreen: Point2D; origPanX: number; origPanY: number; moved: boolean } | { kind: 'vertex'; vertexId: string; anchorOther: Point2D | null } | { kind: 'wall'; wallId: string; startWorld: Point2D; normX: number; normY: number; chainVertices: { id: string; orig: Point2D }[]; moved: boolean; } | { kind: 'opening'; openingId: string; wallId: string } | { kind: 'fixture'; fixtureId: string; offsetX: number; offsetY: number } | { kind: 'electrical'; electricalId: string; offsetX: number; offsetY: number }; Look closely at the kind: 'wall' variant: when you grab a wall segment and slide it perpendicular to its normal (normX, normY), chainVertices stores the original positions of every vertex in its collinear wall chain captured on pointerdown. Moving the pointer computes total offset from startWorld rather than incremental frame deltas — eliminating drift and keeping adjacent corners square even at 120 Hz trackpad rates.
Try the Live 2D/3D Studio
You can test the zero-library 2D CAD canvas, orthogonal/T-junction wall snapping, and instant 3D cutaway sync live in your browser (no signup required to draw) at PlanCaliber.
