Home›Journal›This post

Diffusion-Limited Aggregation in Canvas

Grow organic branches from seeded Brownian walkers, keep neighbor checks fast with a spatial hash, and pair the Canvas edition with a deterministic receipt.

JP
JP Casabianca
AI Engineer and Product Designer · full-stack delivery · Bogotá

Diffusion-limited aggregation creates intricate branching forms from one local rule: random walkers stick when they touch the cluster. This tutorial turns that rule into responsive Canvas generative art with a seeded simulation, spatial hash, bounded work, and a reconstructive export receipt.

Diffusion-limited aggregation grows from local contact

Diffusion-limited aggregation turns a simple rule into coral, frost, lightning, and rootlike structure: release a wandering particle, let it move by Brownian steps, and attach it when it touches the existing cluster. This tutorial builds that fractal growth simulation in Canvas with a seeded generator, bounded work, and an export receipt that can recreate the edition.

The visual appeal comes from tension between randomness and inevitability. Every walker is uncertain, yet attachment happens only at the frontier, so exposed tips receive more traffic and grow faster than sheltered gaps. The result is branching without an explicit branch grammar. Small changes to launch radius, step length, stickiness, or neighborhood produce visibly different material personalities.

Reproducibility begins with seeded randomness for generative art. Record the seed and every parameter before drawing. A screenshot is evidence of appearance; a receipt is evidence of construction. Keeping both lets you curate intuitively while still rebuilding the exact Brownian tree.

A Brownian walker attaches to a diffusion-limited aggregateA luminous branching cluster grows from the left while a dotted wandering path approaches from a launch ring and sticks at an exposed tip.LAUNCHSTICKoccupied clusterseeded Brownian path
Brownian walker becomes branch. Branching emerges from repeated local contact: no explicit tree grammar tells a tip where to grow.
  1. Launch a particle outside the current cluster.
  2. Advance it with seeded random angle steps.
  3. Query nearby occupied buckets.
  4. Attach at contact or discard at a declared bound.

Reading rule: text, order, values, shapes, and line styles carry the conclusion; color is supplementary.

Define the walker and sticking rule precisely

A DLA algorithm needs more precision than “move randomly until close.” Place one occupied seed at the center. Spawn a walker on a circle just outside the current cluster. At each tick, choose an angle from the seeded generator and add a fixed step vector. When the walker enters the sticking radius of an occupied cell, add it to the cluster and update the frontier bounds.

Decide whether contact uses four neighbors, eight neighbors, or Euclidean distance. A grid with four-neighbor contact produces stronger axial bias; eight neighbors soften it but still reveal the lattice. Continuous positions and Euclidean contact look more organic but require a spatial index. This implementation uses continuous walkers and a uniform grid, making the visual smoother while keeping neighbor queries bounded.

The original Witten and Sander paper introduced diffusion-limited aggregation as a model of diffusion-driven growth. Our browser sketch borrows the mechanism, not a claim of physical fidelity. It is an artwork and algorithm study with declared approximations.

Bound Brownian motion without changing the thesis

A naive walker can roam forever. Give every particle a maximum step budget, a launch radius, and a kill radius. If it crosses the kill radius or exhausts its budget, discard it and launch another. Expand launch and kill radii as the cluster grows, while clamping them to the canvas. These bounds guarantee progress for the interface even though an individual walker may fail to attach.

For diffusion-limited aggregation, determinism includes scheduling. Process walkers serially, commit an attachment before launching the next walker, and never let frame duration change how many random numbers one particle consumes. The animation may display different-sized batches on fast and slow devices, but the ordered simulation history must remain identical for the same seed and settings.

The bounds affect texture, so record them. A tight kill radius recycles particles aggressively and can favor exposed tips. A large radius is closer to an open field but costs more steps. Keep a counter for launched, attached, killed, and exhausted walkers; a beautiful image with ninety-nine percent discarded work may need a better launch policy.

Do not interpret a fixed number of simulation ticks as a fixed number of particles. Drive the artwork by an attachment target and cap total launches separately. The receipt should distinguish requested particles from achieved attachments and report whether the run ended by target, launch cap, or time-slice budget.

Use a spatial hash for the growing frontier

Comparing each walker with every attached particle makes diffusion-limited aggregation quadratic. Divide the plane into square buckets slightly larger than the contact diameter. Insert each attached point into one bucket, then test a walker against only its own bucket and the eight neighbors. The query cost follows local density rather than total cluster size.

The spatial hash is part of the artwork's truth boundary. Store exact floating-point positions in the cluster; use integer bucket coordinates only for lookup. Check the real squared distance before sticking. If bucket size, contact radius, and neighbor span disagree, walkers can tunnel through visible branches or stick across gaps.

Audit diffusion-limited aggregation with a tiny known fixture. Insert points on bucket edges, query from every adjacent cell, and confirm the candidate set before distance filtering. Then compare a short seeded run with a slow all-pairs oracle. The optimized search may change performance, but it must not change which particle attaches or where.

This differs from a field-based technique such as curl noise in Canvas. Curl noise gives every point a smooth direction; the Brownian walker has no memory and the aggregate itself shapes future growth by absorbing traffic. That feedback, not just noise, creates the branching silhouette.

Bounded launch, contact, and kill radii for DLAConcentric rings surround a cluster: a contact frontier, launch ring, and kill ring. Counters show attached, killed, exhausted, and total launches.KILL RADIUSLAUNCH RINGCONTACT FRONTIERattached640killed at radius218step exhausted91launch cap1,200
Bounded DLA simulation envelope. Named bounds make the artwork responsive and honest about how many random walkers never join the cluster.
Simulation bounds
BoundPurposeReceipt field
Launch radiusStart near the active frontierlaunch policy
Kill radiusRecycle distant walkerskilled count
Step capEnd wandering particlesexhausted count
Launch capGuarantee whole-run terminationtermination reason

Reading rule: text, order, values, shapes, and line styles carry the conclusion; color is supplementary.

Paint age, exposure, and negative space

The simulation produces coordinates; art direction turns them into a legible edition. Map attachment order to lightness or hue so the seed reads as history and fresh tips read as active growth. Estimate exposure from occupied neighboring buckets, then give isolated frontier points slightly larger or brighter marks. Keep color supplementary by preserving contrast and a silhouette that remains readable in grayscale.

Use a restrained background rather than pure black. Layer a soft radial wash, faint grain generated from the same seed, and the crisp cluster on separate canvases or passes. Avoid blurring the entire result: blur can hide the discrete contact mechanism that makes the piece interesting. A small glow behind the newest frontier is enough.

Negative space is a parameter too. A centered seed creates a medallion; an off-center seed creates directional tension; multiple seeds create competition and eventual bridges. This edition uses one seed because the search intent is understanding the core process. Multi-seed composition belongs in a later variation, not in the base algorithm.

Render Canvas pixels with an explicit scale

Canvas generative art must separate CSS size from drawing-buffer size. Measure the element, multiply by a capped device-pixel ratio, set the backing dimensions, and scale the context once. Store simulation coordinates in a fixed logical view box so resizing redraws the same cluster instead of rerunning it.

Draw batches inside requestAnimationFrame and stop each frame after a small work budget. The UI stays responsive while deterministic state advances in the same order. Pausing must halt the loop without modifying the generator; resuming continues the exact edition. Restarting resets the generator, cluster, counters, and receipt together.

The HTML Canvas element specification defines the bitmap surface and accessibility fallback. Canvas pixels are not an accessible explanation by themselves, so pair the artwork with live counters, a textual method summary, controls with labels, and an exportable receipt. Reduced-motion mode can render a completed bounded edition without animated growth.

A DLA edition pairs its rendered image with a deterministic receiptA cyan branching specimen on the left connects to a structured receipt on the right containing seed, parameters, counts, coordinate digest, and edition identifier.EDITION DLA-6F2Aseedmeadow-17particles640step / contact2.4 / 3.2launches949terminationtargetpoints digest6f2a…91c0
Edition receipt and image. The image carries aesthetic value; the receipt carries reconstructive value. Neither substitutes for the other.
Image
The curated Canvas surface.
Recipe
Seed, random algorithm, dimensions, movement, contact, and bounds.
Outcome
Attachments, discarded walkers, and termination reason.
Identity
A coordinate digest links receipt and edition.

Reading rule: text, order, values, shapes, and line styles carry the conclusion; color is supplementary.

Export the image and its deterministic receipt

Export two linked artifacts: a PNG for the finished surface and JSON for reconstruction. The receipt includes schema version, seed, logical dimensions, random-number algorithm, particle and launch caps, step length, contact distance, launch and kill policies, palette, attachment count, termination reason, and a digest of quantized point coordinates.

Quantization makes the digest portable without pretending floating-point implementations are identical everywhere. The source point array can also be included for exact replay within the lab. Canonicalize object keys before hashing, and label the hash algorithm. The PNG should carry a short edition identifier derived from the same receipt digest so curators can pair image and recipe.

Pixel access enables alternate export and analysis passes. MDN's Canvas pixel manipulation tutorial explains ImageData and image export primitives. In this lab, the browser exports locally; it sends no pixels, parameters, or receipts to a network service.

Tune one variable at a time

Treat the first diffusion-limited aggregation edition as a controlled study. Hold the seed and particle target constant, then vary one parameter. Larger steps make walkers jumpier and can create airy branches. Higher stickiness densifies the frontier. A launch ring close to the cluster accelerates growth but can exaggerate screening. A thicker mark changes the drawing without changing the simulation.

Save each candidate receipt and compare silhouette, branch count, radial occupancy, discard ratio, and elapsed simulation steps. These are descriptive measures, not aesthetic scores. The final choice can remain subjective while its differences stay inspectable. A small multiples sheet often reveals more than endlessly adjusting live sliders.

Diffusion-limited aggregation rewards patience in editing as much as in simulation. Keep surprising asymmetry when it clarifies the growth rule; reject a seed only when the composition fails the intended format, not because it looks insufficiently symmetrical. The receipt makes that curatorial judgment visible without reducing it to a metric.

For neighboring techniques, Worley noise textures organize space by nearest sites, while space-colonization SVG trees grow toward an explicit attraction field. Diffusion-limited aggregation is stranger: random arrivals carve the field indirectly. That is why its branches feel found rather than drafted.

Runnable local artifact — The lab is a generative-art implementation of the DLA mechanism; it is not a validated physical model, does not guarantee bit-identical rasterization across browsers, and performs no network requests.

Plain text1 line
Set a seed and bounded particle target; grow or pause the cluster; inspect attachment and discard counters; export PNG, JSON, or CSV.