Home›Journal›This post

Curl Noise in Canvas: Draw Ink Without Sinks

Derive motion from a seeded scalar potential, measure discrete divergence, compare Euler and RK2, art-direct bounded trails, and export pixels plus recipe.

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

Curl noise turns a smooth scalar potential into a coherent vector field, so Canvas ink can circulate without arbitrary sources and sinks. This tutorial publishes the derivative stencil, measures discrete divergence, compares Euler with RK2 on identical particles, and exports a bounded still beside its complete recipe.

Curl noise begins with a potential, not arrows

Curl noise creates a two-dimensional flow field by differentiating one smooth scalar potential and rotating the gradient. That construction matters: inventing an angle independently at every grid point can make attractive pictures, but it also creates arbitrary sources and sinks. A curl-derived field gives the artist a coherent control surface whose derivative becomes motion.

For a scalar potential ψ(x,y), define the vector field F=(∂ψ/∂y, −∂ψ/∂x). In continuous calculus, its divergence is ∂²ψ/∂x∂y minus the same mixed derivative, so it cancels. A finite grid, boundary rule, noise implementation, and particle integrator introduce error, which is why this tutorial measures discrete divergence instead of declaring perfect incompressibility.

The original curl-noise paper develops divergence-free procedural velocity fields for simulation. This Canvas exercise borrows the mathematical construction for authored ink trails. It is not a fluid solver and does not model pressure, viscosity, density, or Navier–Stokes dynamics.

The deliverable is reproducible creative code: a seeded potential, published derivative stencil, bounded grid and particle count, comparable Euler and midpoint integration, semantic static views, and a PNG beside a JSON recipe. Curl noise becomes useful when the visual mood and the numeric field can both be inspected.

A potential becomes motion by rotating its gradientPotential contours produce a measured gradient; a ninety-degree rotation makes arrows travel along rather than into the scalar slopes.ψ(x,y) → (∂ψ/∂y, −∂ψ/∂x)SCALAR POTENTIALdifferentiateROTATED GRADIENTScale, derivative step, magnitude treatment, and boundary rule remain authored controls.
A potential becomes motion by rotating its gradient. The diagram and visible semantic equivalent state the same conclusion.
  1. Sample one seeded smooth scalar potential.
  2. Estimate x and y derivatives with a published symmetric stencil.
  3. Rotate the gradient ninety degrees.
  4. Keep or normalize magnitude according to the art direction.
  5. Report the derivative step and boundary policy.

Reading rule: labels, symbols, patterns, and structure carry the conclusion; color is supplementary.

Build a seeded smooth scalar potential

Start with deterministic gradient noise. Hash integer lattice coordinates with an explicit seed, assign repeatable gradient directions, interpolate corner contributions smoothly, and combine a small number of octaves. Record scale, octave count, lacunarity, gain, seed, and implementation version. “Random” is not a recipe if reopening the file changes the field.

Ken Perlin’s improved noise paper explains a refined gradient-noise construction and interpolation behavior. The lab uses a compact seeded implementation inspired by that family, not a claim of byte-for-byte equivalence with every library named noise. Version the function because changing its hash or fade curve changes all later artwork.

Sample the potential on a bounded logical domain independent of display pixels. The grid controls diagnostic resolution; the Canvas controls presentation. A high-DPI screen should not silently alter the derivative step or particle paths. Publish the coordinate transform and derivative epsilon in domain units.

This builds on the discipline in seeded randomness for generative art: isolate random streams for field construction, particle placement, and ink styling. With separate streams, changing the palette does not relocate every particle. Curl noise can then be art-directed through the potential’s scale and layering while the initial particle set remains a fair basis for comparison.

Rotate the finite-difference gradient

Approximate derivatives with a symmetric stencil: ∂ψ/∂x≈[ψ(x+h,y)−ψ(x−h,y)]/(2h), and similarly for y. Then rotate, normalize only if the artistic contract calls for constant speed, and multiply by a declared velocity scale. Keeping magnitude preserves potential-gradient strength; normalization emphasizes direction and equalizes travel. Neither is inherently correct.

Publish h because it is a visual parameter as well as a numeric one. Too large a step blurs tight structure; too small a step can amplify floating-point and noise-function artifacts. The potential scale and derivative step must be considered together. Sample a convergence strip at several h values before selecting one.

At boundaries, choose wrap, clamp, reflect, or terminate. Wrapping produces a toroidal domain only if the potential itself tiles; wrapping particle positions over a nonperiodic field creates a seam. The lab terminates trail movement at a padded boundary, freezes that terminal position, and spends the remaining comparison budget on labeled diagnostic samples at the clamped probe.

The earlier flow-field plotter art article turns vector directions into physical marks. Curl noise narrows the field construction: every arrow derives from one scalar potential. The first figure and lab show potential contours beside rotated-gradient arrows, making the relationship visible rather than presenting an unexplained thicket of lines.

Measure discrete divergence honestly

Compute divergence on interior grid cells with the same symmetric family of stencils: ∂Fx/∂x+∂Fy/∂y. Treat the unnormalized construction as the divergence-free flow field under test; report its residual instead of assuming zero. Report mean absolute, root-mean-square, and maximum absolute divergence, plus the number of evaluated cells. Exclude or separately label boundaries where the stencil changes. A single average can hide a severe local defect.

Compare against a deliberately arbitrary direction field sampled at the same resolution. The purpose is not to prove all curl-derived samples are superior, but to make the structural difference testable. Keep scale and magnitude treatment visible; normalizing the vector field after differentiation can introduce divergence even when the unnormalized continuous construction is divergence-free.

Set a tolerance derived from resolution and derivative step, then freeze it in tests. If an implementation change exceeds it, inspect potential sampling, stencil signs, boundary handling, and normalization. Do not quietly loosen the threshold until the picture looks acceptable.

Curl noise remains a discrete approximation. Mixed derivatives cancel under ideal smoothness and consistent operators, while finite precision and sampled noise leave residuals. The divergence view should use a symmetric color scale centered at zero and include numeric extrema. Color alone is insufficient, so the lab also publishes text summaries and a static explanation for readers who cannot distinguish the palette.

Discrete divergence turns a claim into a diagnosticAn arbitrary arrow field contains visible convergence zones while a curl-derived field is paired with a centered residual heatmap and numeric tolerance.SAME GRID · SAME STENCIL · DIFFERENT FIELD CONSTRUCTIONARBITRARY DIRECTIONSsources and sinks can appearCURL-DERIVEDmixed derivatives should cancellocal convergencereport mean · RMS · max residualFinite grids, normalization, boundaries, and integration can reintroduce error.
Discrete divergence turns a claim into a diagnostic. The diagram and visible semantic equivalent state the same conclusion.
Arbitrary field
Independent directions can create uncontrolled convergence and divergence.
Curl-derived field
A rotated gradient has zero continuous divergence under smooth consistent derivatives.
Discrete evidence
Report interior mean, RMS, and maximum residual against a frozen tolerance.
Boundary
The diagnostic is not proof of physical incompressibility.

Reading rule: labels, symbols, patterns, and structure carry the conclusion; color is supplementary.

Advect identical particles with Euler and RK2

Freeze one array of starting particles and one field-evaluation budget. Euler samples velocity once per step, so the lab runs 90 Euler steps. Midpoint RK2 samples an initial velocity and a midpoint velocity, so it runs 45 steps at two samples per step under the same 90-evaluation cap. Both methods therefore perform exactly 90 actual field evaluations per particle. Comparing different starts or evaluation budgets would confound the integrator with the composition.

Record step size, maximum steps, velocity scale, first termination reason, path length, and actual evaluation count. RK2 usually follows curved fields more faithfully per step but costs two field evaluations. This equal-work comparison therefore changes the number of steps, not the step size, and publishes both counts beside the visual result. When a trail reaches a boundary, the lab freezes its position and drawing, then performs the remaining real field samples at a deterministic clamped probe. Active and post-terminal diagnostic evaluations remain separate in the receipt.

Integration can accumulate density and boundary artifacts even when the sampled field has low divergence. Particles are a rendering process, not passive proof of the underlying calculus. Track early exits, boundary contacts, stagnation, and non-finite positions. Clamp work and discard a trail if any coordinate stops being finite.

The line integral convolution art guide offers a texture-based view of vector flow. Particle advection produces authored strokes instead. Use the diagnostic field to validate structure, then treat integrator, step size, stroke opacity, and trail length as explicit style decisions. Curl noise supplies continuity; the ink system supplies rhythm.

Art-direct ink without hiding the field

Separate field parameters from rendering parameters. Field scale, octaves, derivative step, magnitude treatment, and seed determine motion. Particle count, spawn mask, evaluation budget, line width, alpha, blend mode, paper color, and palette determine the mark. This division makes contact sheets meaningful: one column can change the field while another changes only ink.

Use a mask to reserve typography or concentrate flow around a focal region, but label whether the mask affects spawning, velocity, or compositing. A spawn mask changes sampling density; a velocity mask changes the field and may change divergence; a final clip changes only visibility. Those interventions are visually similar and technically different.

The domain-warping marble shader is a useful counterpoint. Domain warping distorts coordinates before sampling a pattern, while curl noise rotates derivatives of a potential to construct motion. Combining them can be expressive, but first keep one operation per diagnostic so a defect has a discoverable cause.

Build a same-seed contact sheet across potential scale, Euler versus RK2, spawn mask, and ink density. Retain the field hash and initial-particle hash. When one panel feels alive, the recipe can state why. Creative judgment remains essential, but it becomes attached to reproducible controls rather than a lucky refresh.

One seed supports deliberate visual comparisonA six-panel contact sheet holds seed, particles, and a 90-evaluation budget constant while field scale, integrator, mask, and ink layers change one at a time.SEED 2048 · SAME STARTS · 90 FIELD SAMPLES EACHSCALE .7EulerSCALE 1.2EulerSCALE 1.2RK2MASK NONERK2MASK OVALRK2INK LAYERSRK2PNG presents the composition; JSON keeps seed, field, integrator, palette, and hashes.
One seed supports deliberate visual comparison. The diagram and visible semantic equivalent state the same conclusion.
  1. Freeze the seed and initial-particle hash.
  2. Vary potential scale to change spatial rhythm.
  3. Compare 90 one-sample Euler steps with 45 two-sample RK2 steps: the same 90-evaluation budget and identical starts.
  4. Label whether masks affect spawning, velocity, or compositing.
  5. Export palette, blend, field, path, and pixel evidence together.

Reading rule: labels, symbols, patterns, and structure carry the conclusion; color is supplementary.

Export pixels beside a complete recipe

Canvas supplies pixel access and serialization mechanics, described in the HTML Canvas pixel-manipulation section. Encoded PNG bytes may vary across browsers, so distinguish a pixel hash computed from ImageData from the file hash of an exported blob. The pixel hash checks the rendered buffer; the recipe reconstructs intent.

Export seed, logical bounds, Canvas dimensions, device scale policy, grid resolution, potential parameters, noise version, derivative stencil and h, vector normalization choice, integrator, step size, particle count, initial-particle hash, palette, blend mode, mask, work caps, divergence summary, and render hash. Reject non-finite numbers before download.

The lab has no animation loop, which avoids motion surprises and makes reduced-motion behavior trivial. A user explicitly regenerates a bounded still. Views of potential, vectors, divergence, and trails share the same recipe; switching views does not consume new random values. Controls have textual labels, results have a live status line, and the artwork includes a semantic description.

Curl noise art should remain portable without implying physical truth. Save the PNG for presentation and JSON for provenance. A screenshot without a seed is an endpoint; a recipe with diagnostics is a system another person can study, vary, and deliberately improve.

Use the field as an artistic instrument

The local lab is a curl noise JavaScript specimen: an unnormalized finite-difference curl diagnostic becomes bounded Canvas ink trails through a separately labeled normalized direction field. It caps the grid, particles, octaves, and field evaluations; derives all randomness from declared seeds; tests finite values and bounds; compares 90 one-sample Euler steps with 45 two-sample RK2 steps over identical initial conditions and the same actual evaluation budget; computes interior divergence against a same-grid arbitrary-angle comparator; and exports PNG plus JSON. The receipt labels active and post-terminal diagnostic work, complete termination counts, field, particle, and pixel hashes, the frozen 0.000001 RMS tolerance, and the exact stencil.

Its truth boundary is equally important. This is procedural, fluid-like mark making, not a Navier–Stokes simulation, proof of incompressibility, or physically calibrated flow. Low discrete divergence under one stencil does not guarantee every normalized, interpolated, integrated, or clipped representation is divergence-free.

Revisit the recipe when the noise implementation, Canvas color behavior, derivative step, grid resolution, integrator, or browser export path changes. Preserve one golden recipe and numeric tolerance so refactors compare the field before aesthetic review. Then inspect the contact sheet at small and large sizes, in forced colors, and at 200% zoom.

The core curl noise method is compact: author a smooth seeded potential, rotate its measured gradient, quantify the discrete residual, advect bounded particles, and keep the recipe beside the pixels. That sequence turns an atmospheric effect into an understandable instrument. The mathematics prevents accidental sinks; the artist still chooses where the ink should breathe.

Runnable local artifact — The lab creates procedural fluid-like art; it is not a Navier–Stokes solver, physical simulation, or proof of continuous incompressibility.

Plain text1 line
Freeze seed and particles, derive a rotated finite-difference gradient, measure interior residuals, integrate bounded trails, and export field and pixel evidence.