Creative Coding From Zero · Episode 06

Fractals & Recursion

Fractals & Recursion is Episode 06 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 06 · Creative Coding From Zero

A function that calls itself can grow a whole forest. That sentence sounds like a riddle the first time you meet recursion, and like the most obvious thing in the world the moment it clicks. The trick fractals teach is this: complexity does not have to be written. You describe one small rule — "a branch is a line, with two smaller branches on its end" — and then you let that rule apply to its own output, over and over, until detail you never typed appears on the screen. Self-similarity. Infinite structure from a handful of lines.

By the end of this episode you'll have a fractal tree that grows branch by branch, re-seedable so every press of the button gives you a new, organic specimen — and an L-system fern, built by a turtle blindly following a rewritten string of letters, that looks like someone drew it by hand. Both run on raw canvas 2D, both are pure recursion, and both are alive on first paint. Step the demo through its six stages and watch a single line segment turn into a botanical garden.

0 fps
canvas 2D · recursion
Seeded jitter on every branch turns the rigid tree into an organic one. Hit regenerate for a new specimen.

What you're looking at

One canvas, one idea, six stages of it. The first three build a tree: a single segment, then a recursive tree that forks perfectly in two, then the same tree with seeded noise shaken through every branch so it stops looking like a circuit diagram and starts looking alive. The last three show that the same recursive move — "do a small thing, then call yourself on the smaller pieces" — also builds the Koch curve (the crinkled edge of a snowflake), the Sierpiński triangle (a triangle riddled with self-similar holes), and finally an L-system plant, where a turtle walks a string of letters that was rewritten from a tiny grammar. The depth slider is the star: drag it and you literally watch detail being born one level at a time.

Everything is driven by the shared mulberry32 seeded RNG, so a given seed reproduces the exact tree — randomness you can reuse. The angle and length-ratio sliders reshape the tree live; on the Koch and Sierpiński stages they politely step aside, because those shapes have a fixed geometry. The tree stages even animate their own growth: depth eases upward on its own, so a fresh load sprouts rather than just appearing.

Stage 1 — One branch

The base unit. A single line segment from a point, at an angle, of some length. There is no recursion here yet — this is just the atom every later stage is made of. It matters because the entire forest is nothing but this one operation, repeated by a function that has learned to call itself. Look at it and say out loud: "a branch is a line." That sentence is about to do a lot of work.

Stage 2 — Recursive tree

Now the magic move. branch() draws one segment, then calls branch() twice from the tip — once rotated left, once rotated right — each call a little shorter than the last. Two becomes four becomes eight. The depth slider sets how many times it's allowed to recurse before it stops. Slide it up and the tree fills in level by level; this is the first time you feel what recursion is — not a loop, but a thing that delegates to smaller copies of itself. Perfectly symmetric, and therefore a little dead. We'll fix that next.

Stage 3 — Randomized tree

Real trees aren't symmetric. So before each child branch, we nudge its angle and length by a small seeded random amount. The result is instantly organic — no two branches alike, yet the whole thing still reads as a tree, because the underlying rule never changed. This is the heart of generative art: a rigid rule plus a pinch of reproducible noise. Hit regenerate for a brand-new specimen; the seed guarantees you could get this exact tree back.

Stage 4 — Koch curve

Same recursive spirit, different rule. Take a line. Replace its middle third with a triangular bump, turning one segment into four. Then do that to all four. Then to all sixteen. The depth slider controls how many subdivisions deep you go. After a few levels the straight line has become an infinitely crinkly coastline — the edge of the Koch snowflake. Notice it has finite area but, in the limit, infinite length. Fractals are full of that kind of mischief.

Stage 5 — Sierpiński

Recursion on a triangle. Draw a triangle, find the midpoints of its three sides, and that carves it into four smaller triangles — recurse into the three corner ones and skip the middle. The skipped middles are the famous holes, and they appear at every scale: zoom into any solid sub-triangle and it's the whole pattern again. Self-similar holes, all the way down (well — down to the depth slider).

Stage 6 — L-system plant

The grand finale, and the most surprising. An L-system is a tiny grammar: start with a seed string, and repeatedly replace each symbol using a rewrite rule. Our rule turns F into a bushy clump like FF+[+F-F-F]-[-F+F+F]. Apply it a few times and you get a long, gnarled string of F + - [ ] characters. Then a turtle reads that string one symbol at a time: F = walk forward drawing, +/- = turn, [ = remember where I am, ] = jump back there. The turtle has no idea it's drawing a plant. It just follows letters — and a fern falls out. Regenerate to jitter the turn angles and grow a different bush from the same grammar.

How the code works

Everything below is the real code from the demo above, lightly trimmed. We'll build it in four moves: the recursive branch, the seeded jitter that makes it organic, the Koch subdivision, and finally the L-system rewrite plus turtle.

(a) The recursive branch — and its base case

This is the whole tree in eleven lines. The base case — if (depth <= 0) return; — is not optional decoration: it's the only thing standing between you and a stack overflow. Every recursive function needs a condition that stops it from calling itself forever. Here, each call shrinks len and decrements depth, so we're always marching toward that exit.

// Draw a branch, then sprout two smaller branches from its tip.
// angle is in RADIANS; canvas y grows downward, so "up" is -y.
function branch(x, y, angle, len, depth) {
  if (depth <= 0 || len < 1) return;        // ← BASE CASE. no exit = stack overflow

  const x2 = x + Math.cos(angle) * len;        // tip of this segment
  const y2 = y + Math.sin(angle) * len;

  ctx.lineWidth = Math.max(0.5, depth * 0.6);     // thicker near the trunk
  ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x2, y2); ctx.stroke();

  const spread = branchAngle;                   // from the slider, in radians
  branch(x2, y2, angle - spread, len * ratio, depth - 1);  // left child
  branch(x2, y2, angle + spread, len * ratio, depth - 1);  // right child
}

// kick it off pointing straight up from the bottom-centre:
branch(W / 2, H * 0.92, -Math.PI / 2, H * 0.22, depth);

Read those two recursive calls and notice what you're not doing: you never write the sub-branches. You describe one level and trust the function to handle the rest of the infinity. That leap of faith is the whole skill.

(b) Seeded jitter for organic trees

The symmetric tree is too perfect. We make it natural by perturbing each child's angle and length with the seeded RNG — and crucially we pass the generator down the recursion so the randomness is deterministic. Same seed, same tree, every time. (Never reach for bare Math.random() here; it would make the tree un-reproducible and break the regenerate button's promise.)

function branchRnd(x, y, angle, len, depth, rnd) {
  if (depth <= 0 || len < 1) return;
  const x2 = x + Math.cos(angle) * len;
  const y2 = y + Math.sin(angle) * len;
  ctx.lineWidth = Math.max(0.5, depth * 0.6);
  ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x2, y2); ctx.stroke();

  // jitter: ± a fraction of the spread / ratio, from the SEEDED stream
  const jA = (rnd() - 0.5) * branchAngle * 0.6;   // angle wobble
  const jL = 0.85 + rnd() * 0.30;                  // length 0.85–1.15×

  branchRnd(x2, y2, angle - branchAngle + jA, len * ratio * jL, depth - 1, rnd);
  branchRnd(x2, y2, angle + branchAngle + jA, len * ratio * jL, depth - 1, rnd);
}

let rnd = mulberry32(seed);          // shared helper — same seed → same forest
branchRnd(W / 2, H * 0.92, -Math.PI / 2, H * 0.22, depth, rnd);

(c) Koch subdivision

The tree forks; the Koch curve bends. Given a segment from a to b, compute the two points one-third and two-thirds along it, then a peak point that sits above the middle (rotate the segment's own vector by -60°). That's four new segments where there was one. Recurse on each.

function koch(ax, ay, bx, by, depth) {
  if (depth <= 0) { ctx.lineTo(bx, by); return; }   // base case: just draw it

  const dx = (bx - ax) / 3, dy = (by - ay) / 3;
  const x1 = ax + dx,       y1 = ay + dy;            // 1/3 point
  const x2 = ax + 2 * dx,   y2 = ay + 2 * dy;        // 2/3 point

  // peak: rotate the (dx,dy) third-vector by -60° and lift it off x1,y1
  const a = -Math.PI / 3;
  const px = x1 + (dx * Math.cos(a) - dy * Math.sin(a));
  const py = y1 + (dx * Math.sin(a) + dy * Math.cos(a));

  koch(ax, ay, x1, y1, depth - 1);   // ╱
  koch(x1, y1, px, py, depth - 1);   //  ╲ up to the peak
  koch(px, py, x2, y2, depth - 1);   //  ╱ down from the peak
  koch(x2, y2, bx, by, depth - 1);   // ╲
}

(d) The L-system: rewrite a string, then walk it with a turtle

An L-system is two halves. First the rewrite: start from an axiom and replace every symbol with its rule, a fixed number of generations. Then the turtle interprets the resulting string. The two characters that make it a plant and not a scribble are [ and ]: they push and pop the turtle's full state (position and heading) onto a stack, so after a side-branch the turtle teleports back to the fork and carries on. Forget the save/restore and your fern collapses into a tangle.

// --- 1. rewrite the string -------------------------------------
const rules = { 'F': 'FF+[+F-F-F]-[-F+F+F]' };   // the whole "DNA"
function expand(axiom, gens) {
  let s = axiom;
  for (let g = 0; g < gens; g++) {
    let next = '';
    for (const ch of s) next += rules[ch] || ch;   // replace F, keep + - [ ]
    s = next;
  }
  return s;                                       // e.g. gens=4 → ~15k chars
}

// --- 2. a turtle interprets it ---------------------------------
function turtle(str, x, y, angle, step, turn, rnd) {
  const stack = [];                               // the state stack for [ and ]
  for (const ch of str) {
    if (ch === 'F') {                            // forward, drawing
      const nx = x + Math.cos(angle) * step;
      const ny = y + Math.sin(angle) * step;
      ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(nx, ny); ctx.stroke();
      x = nx; y = ny;
    } else if (ch === '+') angle += turn + (rnd() - 0.5) * 0.15;  // turn right (+ jitter)
    else if (ch === '-') angle -= turn + (rnd() - 0.5) * 0.15;       // turn left
    else if (ch === '[') stack.push({ x, y, angle });          // PUSH state
    else if (ch === ']') { const s = stack.pop(); x = s.x; y = s.y; angle = s.angle; } // POP
  }
}

That's the entire L-system engine. Change one string in rules and you get a completely different species — algae, a Koch curve, a Penrose tiling — without touching the turtle at all. The grammar is the plant.

Common pitfalls

  • Depth explosion. A binary tree doubles every level: depth 20 is over a million branches, and the browser hangs. Recursion's cost is exponential in depth. Cap it — this demo stops at 12, and even that is a few thousand segments. When something locks up, your first suspect is a depth slider that climbed too high.
  • Missing base case = stack overflow. A recursive function that never hits its stopping condition calls itself until the call stack runs out, and the tab dies with Maximum call stack size exceeded. Always write the if (...) return; first, before the recursive calls — and make sure each call moves toward it (smaller len, lower depth).
  • Degrees vs radians. Math.cos and Math.sin want radians. The angle slider reads in friendly degrees, so convert once at the boundary (deg * Math.PI / 180) and keep everything internal in radians. A tree that comes out as a flat fan or a tight spiral is almost always a missing conversion.
  • The turtle's [ ] stack must save AND restore. [ has to push both position and heading; ] has to restore both. Save position but forget the angle and your side-branches all shoot off the same direction; forget the stack entirely and the turtle never returns to the fork, drawing one long demented squiggle.
  • Growing animation = interpolate depth over time. To make the tree sprout instead of pop, don't redraw at full depth every frame — ease a floating "grow" value from 0 up to the target depth and floor it for the recursion. The reveal of detail level-by-level is what makes it feel alive on load.

Exercises

  1. Animate the tree growing. Add a grow variable that lerps from 0 toward the depth slider's value over a second or two, and pass Math.floor(grow) as the depth. Bonus: fade the newest level's opacity by the fractional part so tips ease in. (The demo already does a version of this — try changing the easing speed.)
  2. Leaves and flowers at the tips. In the branch base case (when depth <= 0), instead of returning silently, draw a small filled circle and pick its color from a palette — e.g. the cosine palette from the authoring brief, indexed by a seeded random t. Suddenly your bare tree blossoms. This is a direct preview of Episode 07.
  3. A second L-system rule. Add a new symbol to the grammar — say a separate rule for X (a common trick: X controls structure, F just draws), like the classic fractal-plant pair X → F+[[X]-X]-F[-FX]+X, F → FF. Swap it in and watch an entirely different fern emerge from the same turtle.

What's next

Episode 07 — Color & Palettes: what separates "frame it" from "AI slop." Our trees so far are a single accent stroke on black, and honestly they'd look ten times better with the right color. Next episode is entirely about that: why random RGB always looks like mud, how cosine palettes and HSL ramps produce harmonious, intentional color, and how to give a generative piece the kind of palette that makes people stop scrolling. Bring the fractal tree — we're going to make it bloom.