Creative Coding From Zero · Episode 13

Tiling & Truchet

Tiling & Truchet is Episode 13 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 13 · Creative Coding From Zero

Draw one small tile — just two quarter-circle arcs in opposite corners. Now stamp it across a grid, and at each cell flip a coin: arcs this way, or that way. That single coin-flip, repeated over a few hundred cells, produces a pattern of interlocking loops and rivers that never repeats and that your eye refuses to stop tracing. It has a name — the Truchet tile, after a French priest who in 1704 catalogued exactly this — and it is the cheapest hypnosis in all of generative art.

This episode is about making infinite, mesmerizing fields out of almost nothing. We start with the classic two-arc weave, then bend the same idea into mazes, multi-scale fractured grids, and — the payoff — smooth Truchet, where the arcs are aligned so precisely that they fuse into long flowing curves wandering across the whole canvas. We finish with Wang tiles, where instead of a random coin-flip we match the edges of neighbours so color and flow stay coherent tile to tile. Everything below is raw <canvas> 2D, fully procedural, and alive on load — the grid keeps quietly re-tiling itself with no input from you. Watch it a moment before you read on.

0 fps
canvas 2D · Truchet
One tile, drawn in both of its orientations.

What you're looking at

Every stage above draws the same kind of object — a square cell holding a motif — onto a regular grid. What changes is (1) which motif, and (2) how we choose its orientation per cell. In Stage 1 you see the atom: a single tile in its two states. By Stage 4 hundreds of those atoms have snapped together into continuous loops. The grid slider sets how many cells fit across; the seed button re-rolls the random choices (and the tiling visibly redraws, proving the seed is what drives the art); palette and weight change the look without touching the structure. The whole field also breathes on its own — every few seconds a fresh seed eases in — so nothing is ever static.

The lesson underneath all six stages is the one that makes tiling magic: local randomness, global structure. Each cell decides on its own, knowing nothing about its neighbours, yet the arcs line up at the shared edges because we designed the tile so they always can. Get the geometry right once and the grid takes care of the rest, forever.

Stage 1 — One tile, two ways

The classic Truchet motif is two quarter-circle arcs, each centred on opposite corners of the cell, with radius equal to half the cell. In orientation A the arcs sit in the top-left and bottom-right corners; in orientation B they sit in the top-right and bottom-left. That's it — two states, a single bit of information per cell. Stage 1 draws both side by side so you can see that each arc enters and leaves its cell exactly at the midpoint of an edge. That midpoint contract is the whole trick: because both orientations touch the same four edge-midpoints, any tile can sit next to any other and the lines still meet.

There's a second Truchet motif worth knowing — a single diagonal line corner to corner, flipped between its two diagonals. It's even simpler and gives a sharp, woven, basket-like look instead of curves. We use it in Stage 3.

Stage 2 — The random weave

Now the payoff of one bit per cell: loop over the grid, and at each cell ask the seeded RNG for a coin-flip. Heads, draw orientation A; tails, B. Render a few hundred cells this way and you get the iconic Truchet maze — a dense tangle of arcs that read as interlocking rings and meandering paths. Crucially it is seeded: the same seed always produces the same tangle, so a piece you like is reproducible. Drag the grid slider up and the same rule scales to a finer, busier weave; drag it down and you can see individual coin-flips.

Stage 3 — Variants & multi-scale

Same machinery, new motifs. First the diagonal-line Truchet (sharp woven look). Then multi-scale: with some probability, instead of drawing a tile in a cell we subdivide that cell into a 2×2 block of smaller tiles and recurse. The result is a fractured field where calm large loops sit beside busy detailed knots — a single rule producing several visual densities at once. Because the recursion is driven by the same seeded RNG, the fracture pattern is reproducible too.

Stage 4 — Smooth Truchet (the flowing curves)

This is the one people screenshot. We keep the two-arc tile but change nothing about how arcs are drawn — they were always quarter-circles centred on corners, meeting at edge-midpoints. The realization is that those midpoints are shared between neighbours. So when tile A's arc leaves through its right edge at the midpoint, and the tile to its right has an arc entering its left edge at the same midpoint, the two arcs are tangent and fuse into one continuous curve. Across the whole grid the arcs braid into long sweeping rivers and closed loops. No extra code — it emerges purely from the midpoint contract. Watch one curve and try to follow it to its end; that compulsion is the entire appeal of the form.

Stage 5 — Wang tiles (matching edges)

A coin-flip per cell is locally random but globally featureless. Wang tiles add coherence: give every edge a color, and only place a tile if its left edge matches the right edge of the tile already to its left, and its top matches the bottom of the tile above. Color and flow then propagate across the field instead of resetting at every cell. We assign each cell two edge-colors (one for the horizontal flow, one for the vertical) so neighbours always agree, then draw arcs tinted by those edge colors — so you can literally watch a color stream snake tile-to-tile. This is the same idea that underpins next episode's wave function collapse, in miniature.

Stage 6 — Styled & alive

Finally, the look. Smooth Truchet plus a chosen palette, a tuned line weight, a soft glow, and a gentle animated re-tile: every few seconds the seed advances and the new field cross-fades in, so the curves slowly rewrite themselves. Hit save PNG to export the current frame at full device resolution — these make genuinely nice wallpapers. This stage is the others, dressed up; the structure is identical, only the presentation changed.

How the code works

Four ideas carry the whole episode. First, drawing one tile. A tile is a square of side s at pixel (x, y). Orientation A puts arc centres at the top-left and bottom-right corners; orientation B at the top-right and bottom-left. Each arc has radius s/2, so it spans from one edge-midpoint to the neighbouring one:

// One Truchet tile: two quarter-circle arcs, orientation 0 or 1.
function truchetArcs(ctx, x, y, s, orient) {
  const r = s / 2;                 // radius = HALF the cell — this is the contract
  if (orient === 0) {
    // arcs hug the top-left and bottom-right corners
    ctx.beginPath();
    ctx.arc(x,     y,     r, 0,            Math.PI / 2);   // TL corner
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(x + s, y + s, r, Math.PI,        1.5 * Math.PI); // BR corner
    ctx.stroke();
  } else {
    // arcs hug the top-right and bottom-left corners
    ctx.beginPath();
    ctx.arc(x + s, y,     r, Math.PI / 2,    Math.PI);        // TR corner
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(x,     y + s, r, 1.5 * Math.PI,  2 * Math.PI);    // BL corner
    ctx.stroke();
  }
}

Second, the grid loop with seeded orientation. We make one mulberry32 stream from the seed and pull a coin-flip per cell. Because the stream is deterministic, the same seed reproduces the same field — and re-seeding visibly redraws it:

// Stamp the tile across an n×n grid, orientation chosen by seeded RNG.
const rnd = mulberry32(seed);          // one stream for the whole field
const s = size / n;                     // cell side in pixels
for (let gy = 0; gy < n; gy++) {
  for (let gx = 0; gx < n; gx++) {
    const orient = rnd() < 0.5 ? 0 : 1;  // one bit per cell
    truchetArcs(ctx, gx * s, gy * s, s, orient);
  }
}

Third, the smooth-connection trick — which, delightfully, is not a trick at all but a consequence of the radius being exactly s/2. An arc centred on a corner with that radius crosses each adjacent edge at its midpoint, and it crosses perpendicular to the edge. The neighbouring cell's arc, entering the same midpoint, is also perpendicular there. Two curves meeting at a point with the same tangent are smooth — so the join is seamless automatically:

// Why arcs connect: an arc of radius s/2 centred on a corner
// passes through the midpoints of its two adjacent edges...
const r = s / 2;
// corner (x, y), edge midpoint to the right is (x + s/2, y):
//   distance from corner = s/2 = r   → arc lands exactly there
//   and the arc's tangent at that point is vertical = ⟂ to the edge.
// The neighbour's arc enters the SAME midpoint, also ⟂ → tangent match
// → one continuous curve. Use r ≠ s/2 and you get visible seams.
if (Math.abs(r - s / 2) > 1e-6) console.warn('seams ahead');

Fourth, Wang edge-matching. We give every grid line a color so that any two cells sharing an edge necessarily read the same color there. The cleanest way: derive each cell's four edge-colors from per-grid-line values. Cell (gx, gy) takes its left edge from vertical line gx and its right from line gx+1; its neighbour to the right takes its left from that same line gx+1. Shared line ⇒ shared color ⇒ a coherent flow:

// Wang tiles: edge colors come from grid LINES, so neighbours agree.
const vcol = [], hcol = [];                 // colors on vertical / horizontal lines
for (let i = 0; i <= n; i++) vcol[i] = (rnd() * K) | 0;  // K edge colors
for (let j = 0; j <= n; j++) hcol[j] = (rnd() * K) | 0;

for (let gy = 0; gy < n; gy++) {
  for (let gx = 0; gx < n; gx++) {
    const left = vcol[gx], right = vcol[gx + 1];   // shared with L/R neighbours
    const top  = hcol[gy], bot   = hcol[gy + 1];   // shared with U/D neighbours
    // orientation + tint chosen from these four matching colors
    drawWangCell(ctx, gx, gy, s, left, right, top, bot);
  }
}

Common pitfalls

  • Seams where arcs should meet. The single most common Truchet bug. Arcs only fuse if the radius is exactly half the cell, so each arc lands on the edge midpoint. Use r = s * 0.4 or s * 0.6 and every join shows a gap or a kink. If your cell size s = size / n isn't a whole number, rounding can also nudge arcs off the midpoint — round the cell size, not each arc, or draw on a DPR-scaled context so sub-pixel positions stay consistent.
  • Math.random() in the art path. Reach for the global RNG and your "favourite" tiling vanishes on the next load and can never be recovered. Always pull from a seeded mulberry32 stream so a seed reproduces the exact field — and so the regenerate button means something.
  • Runaway subdivision. Multi-scale recursion that subdivides with fixed probability and no depth cap can, on an unlucky seed, recurse far too deep and stall the frame. Always pass a depth and stop (e.g. at depth 2–3); taper the subdivide probability with depth so deep splits get rare.
  • Muddy color / heavy look. Random RGB per arc reads as noise. Drive color from a cosine palette indexed by position or edge-color, and keep the line weight proportional to the cell size (lineWidth = s * weight) so the pattern stays legible whether the grid is coarse or fine. Round line caps (ctx.lineCap = 'round') hide tiny join errors and read as softer.
  • Edge mismatches in Wang tiles. If you store an edge color per cell (four values each) you have to keep neighbours in sync manually and one off-by-one breaks the flow. Store colors on the shared grid lines instead, as above, and matching is automatic by construction.

Exercises

  1. Hex Truchet. Swap the square grid for a hexagonal one. Each hex has six edges, so the motif becomes three arcs connecting pairs of edge-midpoints, and there are more than two orientations. Lay out hex centres (offset every other row), keep the radius tied to the edge-midpoint distance, and watch a denser, honeycomb-flavoured weave appear.
  2. A maze you can solve. Use the diagonal-line variant but treat each tile as a wall segment, then carve a guaranteed path: run a seeded depth-first or randomized-Prim maze to decide which cells connect, and pick each tile's orientation to keep the corridor open. Now the hypnotic pattern is also a real labyrinth with an entrance and an exit.
  3. Animate orientations with noise. Replace the per-cell coin-flip with a value-noise field sampled at the cell centre plus a slowly advancing time offset (noise(gx*f, gy*f + t) > 0 ? A : B). The orientations now flip in smooth travelling waves instead of all at once, so the whole weave ripples and reorganizes continuously — copy makeNoise from the authoring brief.

What's next

Episode 14 — Wave Function Collapse. Wang tiles hinted at it: instead of choosing each cell independently, we let constraints between neighbours decide what's allowed, then collapse the grid one cell at a time — picking the most-constrained cell, committing to a tile, and propagating the consequences outward. The same edge-matching idea, turned into a tiny solver that grows coherent, surprising worlds from a handful of tiles. If you liked watching Wang colors flow tile-to-tile, you'll love watching a whole field resolve itself.