Generative Art — Creative Web

Generative art = rules you write + random numbers for the details. min + rand() * (max - min) gives a range, Math.floor(rand() * n) gives an index…

Raka tells his assistant: "lay 140 coffee beans on the fabric, ten to a row; each bean may shift a little, tilt any way it likes, and take its colour from the three inks". The rules are Raka's, the details are the assistant's. The result is different every time, unless the assistant follows one book of random numbers, opened at the same page. That page number is called the seed.

That's generative art: a picture made by rules you write, with random numbers filling in the details. This lesson makes the Bean Pattern, the motif for Raka's next shirt run: the coffee beans from the coffee print, laid out by code across an A4 print area, then exported as a 300 DPI print file.

Rules and randomness

We draw in millimetres: the A4 print area is 210 × 297. The rules:

Rule (always the same) Randomness (different for each bean)
10 columns × 14 rows = 140 beans, 21 mm apart x and y shift, up to 4 mm
bean shape: an oval with a crease down the middle radius 6 to 8 mm
shirt-black background tilt angle
colours from Raka's ink palette which colour from the palette

rand() here is a function that returns a fraction from 0 up to below 1, like Math.random(). Every range is built from it:

const SHIRT = '#1c1917', CREAM = '#f5e6c8', BROWN = '#c47a3d', GREEN = '#7fb069';
// brown 3 out of 6, cream 2 out of 6, green 1 out of 6
const PALETTE = [BROWN, BROWN, BROWN, CREAM, CREAM, GREEN];

const dx = (rand() * 2 - 1) * 4;                            // -4 up to below 4 mm
const r = 6 + rand() * 2;                                   // 6 up to below 8 mm
const color = PALETTE[Math.floor(rand() * PALETTE.length)]; // index 0 to 5

Seed: randomness you can repeat

Math.random() can't be given a seed. Every call takes a new number from the browser's own generator, and there is no way to replay the sequence. So once Raka has approved the pattern on screen and the same code draws it again for the print file, every number is new: the print file is another pattern, not the one Raka approved.

The fix is a PRNG (pseudo-random number generator) you write yourself. Its numbers look random, but they are computed from the seed, so the same seed always gives the same sequence. mulberry32 takes 8 lines:

function mulberry32(seed) {
  return function rand() {
    seed |= 0;
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296; // 0 up to below 1
  };
}
1st rand() 2nd 3rd
mulberry32(42) 0.6011 0.4483 0.8525
mulberry32(42) again, tomorrow, on another phone 0.6011 0.4483 0.8525
mulberry32(7) 0.0117 0.0620 0.9769

Noise: smooth randomness

Numbers from rand() don't know each other: the bean next door can tilt any way at all. Noise gives smooth random numbers: two points close together get similar values, so neighbouring beans tilt the same way, as if carried by a current.

What we write here is value noise: random numbers are placed on the whole-number points of a grid (the lattice), and the values in between are smoothed. Perlin noise (Ken Perlin, 1983) places random directions (gradients), not numbers, on the lattice points, and looks more natural; simplex noise is its successor. The idea is the same: close neighbours, similar values.

function makeNoise(rand) {
  const N = 16;
  const lattice = [];
  for (let i = 0; i < N * N; i++) lattice.push(rand()); // 256 random numbers on the lattice points
  const v = (x, y) => lattice[(y % N) * N + (x % N)];
  const smooth = (t) => t * t * (3 - 2 * t);         // smoothstep: slow at the ends
  return function noise(x, y) {
    const x0 = Math.floor(x), y0 = Math.floor(y);
    const tx = smooth(x - x0), ty = smooth(y - y0);
    const top = v(x0, y0) + (v(x0 + 1, y0) - v(x0, y0)) * tx;
    const bottom = v(x0, y0 + 1) + (v(x0 + 1, y0 + 1) - v(x0, y0 + 1)) * tx;
    return top + (bottom - top) * ty;               // 0 to 1
  };
}

One dimension first: lattice point x = 2 holds 0.2 and x = 3 holds 0.8. At x = 2.25, t = 0.25 and smooth(0.25) = 0.156, so the noise = 0.2 + 0.6 × 0.156 = 0.29. A plain straight line would give 0.35; smoothstep makes the value turn gently near the lattice points, so there are no sharp corners.

When noise is used as the angle at every point, it's called a flow field: a map of which way the current runs. Each bean just follows the direction at its position.

Other options: you don't have to write mulberry32 and makeNoise yourself.

Way When to pick it
Write it yourself (this lesson) small code with no library, and you know the exact order of rand() calls. Pick this for learning and for Raka's print file
p5.js 2.4 (a library for creative coding) quick sketches. randomSeed(42) makes random() repeatable, random(10, 20) gives a range, random(['a', 'b', 'c']) picks an array item, and noiseSeed() + noise(x, y) give smooth noise. The numbers differ from mulberry32(42), because the generator is different

The Bean Pattern, complete

bean() is the function from the Canvas API Basics lesson, now with the radius and colour as parameters. ctx must already be set so that 1 unit = 1 mm (see the next section).

function bean(ctx, x, y, angle, r, color) {
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(angle);
  ctx.scale(1, 0.62);                 // the circle becomes an oval
  ctx.beginPath();
  ctx.arc(0, 0, r, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
  ctx.beginPath();                    // the bean's crease
  ctx.moveTo(-r * 0.7, 0);
  ctx.lineTo(r * 0.7, 0);
  ctx.strokeStyle = SHIRT;
  ctx.lineWidth = r * 0.25;
  ctx.stroke();
  ctx.restore();
}

function drawPattern(ctx, seed, jitter) {   // jitter: 0 = rigid grid, 1 = full shift
  const rand = mulberry32(seed);
  const noise = makeNoise(rand);           // uses the first 256 numbers
  ctx.fillStyle = SHIRT;
  ctx.fillRect(0, 0, 210, 297);
  for (let row = 0; row < 14; row++) {
    for (let col = 0; col < 10; col++) {
      const dx = (rand() * 2 - 1) * 4 * jitter;
      const dy = (rand() * 2 - 1) * 4 * jitter;
      const r = 6 + rand() * 2;
      const randomAngle = rand() * Math.PI * 2;   // always called, see Common traps
      const color = PALETTE[Math.floor(rand() * PALETTE.length)];
      const x = 10.5 + col * 21 + dx;
      const y = 12 + row * 21 + dy;            // 14 × 21 = 294 mm, 1.5 mm left at top and bottom
      const angle = noise(x / 30, y / 30) * Math.PI * 2;
      bean(ctx, x, y, angle, r, color);
    }
  }
}

Exporting at 300 DPI for printing

DPI (dots per inch) is the number of pixels per inch of fabric. Screen printers usually ask for 300. 1 inch = 25.4 mm:

mm inches pixels at 300 DPI
A4 width 210 8.27 2,480
A4 height 297 11.69 3,508

This is the setTransform trick from the Canvas API Basics lesson: on screen 1 mm = 1 CSS px (setTransform(dpr, 0, 0, dpr, 0, 0)), for print 1 mm = 11.81 pixels. The drawing function is the same, the seed is the same, the order of rand() calls is the same, so the pattern is exactly the same, only sharper.

function exportPrint(seed, jitter) {
  const pxPerMm = 300 / 25.4;                     // 11.81
  const printCanvas = document.createElement('canvas');
  printCanvas.width = Math.round(210 * pxPerMm);  // 2480
  printCanvas.height = Math.round(297 * pxPerMm); // 3508
  const ctx = printCanvas.getContext('2d');
  ctx.setTransform(pxPerMm, 0, 0, pxPerMm, 0, 0);
  drawPattern(ctx, seed, jitter);
  printCanvas.toBlob((file) => {
    const a = document.createElement('a');
    a.href = URL.createObjectURL(file);
    a.download = `bean-pattern-seed-${seed}.png`;
    a.click();
  }, 'image/png');
}

⚠️ Common traps in the pattern and the print file

TL;DR: Generative art = rules you write + random numbers for the details. min + rand() * (max - min) gives a range, Math.floor(rand() * n) gives an index. Math.random() can't be replayed; a PRNG like mulberry32 always gives the same sequence for the same seed (seed 42: 0.6011, 0.4483, 0.8525), as long as the order of rand() calls doesn't change. Plain random jumps around; noise (value noise here, Perlin and simplex are smoother) gives similar values to nearby points, and noise used as an angle is a flow field. For a 300 DPI print, A4 210 × 297 mm = 2,480 × 3,508 pixels: draw in mm, then setTransform(300 / 25.4, 0, 0, 300 / 25.4, 0, 0), toBlob, and keep the seed.

⚡ Your rules, random details

Write:

const dx = (rand() * 2 - 1) * 4;                            // -4 up to below 4 mm
const r = 6 + rand() * 2;                                   // 6 up to below 8 mm
const color = PALETTE[Math.floor(rand() * PALETTE.length)]; // index 0 to 5
Guess first: what does for (let i = 0; i < 5; i++) ctx.fillRect(Math.random() * 400, 200, 10, 10) draw?

5 squares of 10 × 10 at random x between 0 and 400, all at y = 200: one horizontal row with uneven gaps.

Meaning: min + rand() * (max - min) gives a number between min and max, and Math.floor(rand() * n) gives an index from 0 to n - 1.

⚡ Seed: randomness you can repeat

Write:

const rand = mulberry32(seed);
Guess first: the pattern Raka approved on screen is drawn again with Math.random() for the print file. Is it the same?

No. Every number is new, so the print file is another pattern, not the one Raka approved.

Meaning: A PRNG like mulberry32 always gives the same sequence for the same seed, as long as the order of rand() calls doesn't change. Keep the seed, not just the picture.

⚡ Noise: smooth randomness

Meaning: Numbers from rand() don't know each other. Noise gives similar values to points close together, so neighbouring beans tilt the same way. Noise used as an angle is called a flow field.

⚡ Printing at 300 DPI

Write:

ctx.setTransform(pxPerMm, 0, 0, pxPerMm, 0, 0);

Meaning: Draw in mm, then scale up: A4 210 × 297 mm becomes 2,480 × 3,508 pixels. The seed and the order of rand() are the same, so the pattern is exactly the same, only sharper.

What you will learn