DEV Community

Cover image for Building Non-Square Grids & Fair Isle Float Checks in HTML5 Canvas
Fatt Coder
Fatt Coder

Posted on

Building Non-Square Grids & Fair Isle Float Checks in HTML5 Canvas

If you have ever built a pixel-art editor on HTML5 Canvas, you probably assumed cellWidth === cellHeight. That assumption breaks immediately if you build a tool for knitters.

A knitted stockinette stitch is wider than it is tall. At a standard gauge of 20 stitches by 26 rows per 10 cm, the visual aspect ratio of a single cell is roughly 1.25 : 1 (often referred to by knitters as a 4:5 height-to-width stitch ratio). Render a knitting chart on square pixels and every circular motif turns into a squashed oval once knitted.

While looking at how small vertical web apps handle domain constraints without a backend, I spent some time inspecting a browser-local knitting chart maker that runs entirely on HTML5 Canvas and localStorage—handling 8×8 to 60×60 grids, four gauge aspect ratios (4:5, 5:6, and 1:1), client-side 2–8 color image quantization, and live Fair Isle float detection.

Two pieces of logic are especially neat to implement in plain TypeScript: non-square pointer-to-cell mapping (with bottom-up, right-to-left knitting coordinates) and a linear-time float-length scanner.

1. Mapping Canvas Coordinates to Knitting Rows & Stitches

Unlike screen coordinates where (0, 0) is top-left, knitting charts put Row 1 at the bottom and Stitch 1 on the right (for right-side rows and circular knitting). Combine that with rectangular cells and your hit-testing math looks like this:

type GaugePreset = 'stockinette' | 'worsted' | 'bulky' | 'square';

const ASPECT_RATIO: Record<GaugePreset, number> = {
  stockinette: 4 / 5, // height / width (20 sts x 26 rows)
  worsted: 5 / 6,     // 18 sts x 24 rows
  bulky: 4 / 5,       // 14 sts x 18 rows
  square: 1,          // crochet / cross-stitch
};

export function pointerToKnittingCell(
  mouseX: number,
  mouseY: number,
  cols: number,
  rows: number,
  cellW: number,
  preset: GaugePreset
) {
  const cellH = cellW * ASPECT_RATIO[preset];
  const colFromLeft = Math.floor(mouseX / cellW);
  const rowFromTop = Math.floor(mouseY / cellH);

  if (colFromLeft < 0 || colFromLeft >= cols || rowFromTop < 0 || rowFromTop >= rows) {
    return null;
  }

  return {
    // Bottom-up row index (1-based)
    row: rows - rowFromTop,
    // Right-to-left stitch index (1-based)
    stitch: cols - colFromLeft,
    arrayRow: rowFromTop,
    arrayCol: colFromLeft,
  };
}
Enter fullscreen mode Exit fullscreen mode

2. Detecting Long Floats (> 5 Stitches)

In stranded Fair Isle knitting, carrying an unused yarn color behind the fabric for more than 5 stitches creates loose loops ("floats") that snag or pull the fabric tight. Checking every row on edit is a straightforward O(R × C) scan:

export interface FloatWarning {
  row: number;
  maxRun: number;
  color: string;
}

export function scanLongFloats(grid: string[][], maxSafeSpan = 5): FloatWarning[] {
  const warnings: FloatWarning[] = [];
  const totalRows = grid.length;

  grid.forEach((rowCells, idx) => {
    // Only warn if the row actually uses 2+ colors
    if (new Set(rowCells).size < 2) return;

    let currentColor = rowCells[0];
    let run = 1;
    let longestRun = 1;
    let longestColor = currentColor;

    for (let c = 1; c < rowCells.length; c++) {
      if (rowCells[c] === currentColor) {
        run++;
        if (run > longestRun) {
          longestRun = run;
          longestColor = currentColor;
        }
      } else {
        currentColor = rowCells[c];
        run = 1;
      }
    }

    if (longestRun > maxSafeSpan) {
      warnings.push({
        row: totalRows - idx, // bottom-up knitting row number
        maxRun: longestRun,
        color: longestColor,
      });
    }
  });

  return warnings;
}
Enter fullscreen mode Exit fullscreen mode

Where Browser-Only Tools Hit Their Ceiling

Keeping everything in Canvas + localStorage avoids server bills, upload privacy headaches, and login friction—unlike subscription web suites such as StitchFiddle or desktop tools like Stitchmastery.

The trade-off is scope. Bounding grids to 60×60 keeps live V-stitch canvas redraws snappy on every mouse drag, but rules out full-sweater photographic intarsia charts. Without a backend or a vector scene graph, exports also tend to stop at raster PNG and browser Print/PDF rather than editable SVG or auto-generated written instructions. And because localStorage is tied to one browser profile, users still need manual PNG exports—or ideally a JSON import/export button—if they switch devices.

Honestly, for anyone building niche web utilities, this is a useful reminder: half the value isn't fancy UI, it's encoding the weird physical rules of the craft (4:5 cells, bottom-up axes, 5-stitch floats) right into the canvas loop.

Top comments (0)