Compiled L-system turtle

L-system Garden

Fractal plants, bushes, saplings and stochastic trees grow from their roots outward and sway together in a soft noise wind.

Parameters

Seed – Saved in the address bar, so a link reproduces this variation. Keys on the canvas: Space, R, N, F.

How it works

Each plant starts from an axiom and a set of rewriting rules, for example X -> F+[[X]-X]-F[-FX]+X and F -> FF for the fractal plant. The tree grammar is stochastic: each F picks one of four productions at random, so no two trees match. After four to six rewrites the string holds thousands of symbols.

The string is compiled once into typed arrays of turtle ops: forward (runs of F merged into one segment with slightly jittered length), turn (with a jittered angle), push, pop and tip. A single pass records each op's bracket depth and its path length from the root, and measures the rest pose so the plant can be scaled to fit its slot.

Every frame the turtle re-runs the program with a small stack in a Float32Array. Growth is a front that advances along path length: a segment is drawn only as far as front - distance allows, so all branches extend at once, the way a real plant grows, instead of being drawn one stroke after another. Blossoms open at branch tips once the front has passed them.

Wind is a bend added to the heading on every forward step, proportional to segment length and increasing with depth, so the trunk barely moves and outer twigs swing. Its strength mixes simplex noise over time with a slow sine and any gust you add by sweeping the pointer across the garden.

Segments are collected into one Path2D per depth, each stroked with its own width (shrinking by about a third per level) and a colour blended from bark to leaf. The sky, hills and ground are pre-rendered once per season; grass blades and the drifting pollen or fireflies are drawn live.

  • l-system
  • turtle graphics
  • stochastic grammar
  • Path2D
  • wind

Source

/assets/demos/canvas2d/l-system.js

More Canvas 2D demos