noise
Worley Noise
- Published
- 2020-12-25
- Tags
- p5.js, noise, algorithm, worley noise
On my ongoing learning path in the Creative Coding Arts I’m going to make a lot of stops at a bunch of Clichés. I’ve been saying that this is, for me, the equivalent of the “Create a Blog in 5 Minutes with Framework X” of the Web Development scene. This time, the Cliché’s name is Worley Noise and I got to it via another Coding Train episode.
Worley Noise’s algorithm works as follows:
- We randomly create and distribute feature points (I called them control points in the code for whatever reason)
- With that out of the way, we draw a picture where, for every pixel, we calculate the distance to the feature points
- We then map - somehow - that distance to a given color and move on to the next pixel
The result is sometimes alike cells, other times it resembles crystals , it really depends how you approach the color mapping and which distance you decide to use.
I started this exercise off with a simple enough code where I had an array of points distributed randomly across the screen and I went around every pixel on the screen making stroke / point calls to p5.js until the picture was formed. It worked but it was very very slow, so I took a little bit of time to try and make it a little bit better, and although I managed to get a full picture rendered from 12 seconds down to 3s - on my computer, which is a blessing because there’s a GPU available, but also a curse because it’s a 5k display and so the canvas is very large - it’s still slow enough that I didn’t even consider adding animation to this experiment.
In terms of “optimizations” I did a couple of things:
- Instead of using P5.js
stroke/pointmethods, I manipulate the pixel array directly, which in turn makes the code an estimated 94.55% less unreadable as we need to navigate a one-dimensional, pixel density aware, 4 color element array instead of just saying “draw this pixel this color” - I also went with the cell approach to the feature points, where instead of having an array of randomly generated points, I now break down the canvas in a grid and randomly place a point in each grid element. This in turn makes the lookups faster as I can address specific grid cells instead of going over all the points.
I also made a few variations in Color Schemes, some are black and white and simply look at the distance to closest point, others - like the Oily ones - look at different distances for the different color components. I didn’t put a lot of science into it, I just have an easy way to add color schemes and played around with them until something visually interesting came out.
As usual the code lies bellow, for the other experiments I’ve been transpiling the ES6 code into more compatible Javascript but I figured I would start serving ES6 code directly instead as most things should be available for most browsers anyway.
If I ever manage to make this code run faster, I’ll definitely explore adding animation to this - be it that the points move around or that I map things in a 3D space and navigate that.
Links:
- Worley Noise Wikipedia Page
- The Book of Shaders - Cellular Noise
- Coding in the Cabana 4: Worley Noise
Update, October 2026
“If I ever manage to make this code run faster, I’ll definitely explore adding animation.” Well, it took almost six years and some help from Claude, but here we are :)
The slowness turned out to be mostly small things adding up. For every pixel I was building a fresh list of distances, sorting it, and then working out the colour once for every physical pixel on a high density screen rather than once per pixel. Now each pixel just keeps track of its three smallest distances as it checks the points around it, and the result is computed at a lower resolution (the Pixel Size slider) and stretched over the canvas. A full frame takes under 10 milliseconds, so the points finally move: each one wanders around inside its own grid cell, which keeps the “only look at the neighbouring cells” trick working.
Once the code was in pieces, it was easy to untangle a few things I’d baked into each colour scheme. There’s now a Pattern picker for which distance you look at (the nearest point, the second nearest, or the difference between them, which draws the edges between cells), and a Distance picker, because “distance” doesn’t have to mean a straight line. Measured like a taxi driving around city blocks (Manhattan) or like a king moving on a chessboard (Chebyshev), the cells come out diamond-shaped or square instead of round:
The Edges pattern is my favourite, and it’s the one that looks most like cracked earth or a dragonfly’s wing. There’s also a seed, cell size and speed, an invert switch, and a toggle to show the points themselves, which makes it much clearer what’s going on.
Source — sketch.js
'use strict'
// Worley (cellular) noise. Feature points are scattered over the canvas, one
// in each cell of a grid, and every pixel is coloured by its distance to the
// nearest of them (F1), the second nearest (F2), or a mix. Each point drifts
// around inside its own cell, so the pattern moves.
// Avoiding Global Mode: https://github.com/processing/p5.js/wiki/Global-and-instance-mode
const experiment = ( sketch ) => {
//
// Configuration
//
let container = document.getElementById('sketch-holder')
let canvas_el
let cell_size = 90 // Size of the grid that places one feature point per cell, in pixels
let pixel_size = 2 // Size of one computed block, in pixels: 1 is every pixel
let speed = 0.01 // How fast the points drift, zero freezes them
let pattern = 'cells'
let metric = 'euclidean'
let invert = false
let show_points = false
let time = 0
// The same seed gives the same points
let seed = Math.floor(Math.random() * 1000000)
// One entry per slider: its [min, max, step], where its value lives and
// what a new value does. Each one is wired to the elements named after it,
// "cell_size" to #experiment-control-cell-size and its label
// #experiment-label-cell-size
let sliders = {
cell_size: { range: [20, 240, 5], value: () => cell_size, update: value => { cell_size = value; placePoints() } },
pixel_size: { range: [1, 8, 1], value: () => pixel_size, update: value => { pixel_size = value } },
speed: { range: [0, 0.05, 0.001], value: () => speed, update: value => { speed = value } }
}
// What each pixel's value is made of. f1, f2 and f3 are the distances to
// the nearest, second and third nearest points, in cells (so 1 is one
// cell's width); each pattern turns them into a value from 0 to 1.
let patterns = {
cells: { label: "Cells (F1)", value: (f1, f2, f3) => f1 },
crystals: { label: "Crystals (F2)", value: (f1, f2, f3) => f2 / 1.4 },
edges: { label: "Edges (F2 − F1)", value: (f1, f2, f3) => Math.min((f2 - f1) * 2, 1) },
oily: { label: "Oily (F1, F2, F3 as red, green, blue)", rgb: true }
}
// How "distance" is measured. Each one gives the cells a different shape:
// round, diamond or square.
let metrics = {
euclidean: { label: "Euclidean (round)", distance: (dx, dy) => Math.sqrt(dx * dx + dy * dy) },
manhattan: { label: "Manhattan (diamond)", distance: (dx, dy) => Math.abs(dx) + Math.abs(dy) },
chebyshev: { label: "Chebyshev (square)", distance: (dx, dy) => Math.max(Math.abs(dx), Math.abs(dy)) }
}
// Color Schemes
//
// `stops` are the colours a value runs through from 0 (on top of a point)
// to 1 (far from any); any number of stops, blended evenly. The two "site"
// schemes use the site's own palette. "Oily" ignores them.
let color_scheme
let color_sets = {
site_dark: {
label: "Site Dark",
stops: ["#ffd9b8", "#ff6600", "#5c2a06", "#0a0a0a"]
},
site_light: {
label: "Site Light",
stops: ["#b84900", "#ff9a52", "#ffe6d4", "#ffffff"]
},
greyscale: {
label: "White Blobs",
stops: ["#ffffff", "#000000"]
},
lava: {
label: "Lava",
stops: ["#ffffff", "#ffd23f", "#ff3d00", "#5c0a0a", "#000000"]
},
green_crystal: {
label: "Green Crystals",
stops: ["#00ff66", "#0f5132", "#000000"]
}
}
// Each scheme's colours as a lookup table of 256 RGB triplets, so
// colouring a pixel is an array read rather than a blend
const SHADES = 256
let palettes = {}
// The feature points. Each one belongs to a grid cell and stays inside
// it, which is what lets a pixel find its nearest points by checking only
// the cells around its own, instead of every point there is.
let points = []
let grid_cols = 0
let grid_rows = 0
// How many cells out from its own a pixel looks. The nearest point is
// almost always within one cell, but the second and third nearest can be
// two away, and the Crystals, Edges and Oily patterns need those right
const SEARCH = 2
// The picture, one pixel per block, drawn scaled up to fill the canvas
let noise_image
// Controls
let controls = {
color_scheme_picker: document.getElementById("experiment-control-color-scheme"),
pattern_picker: document.getElementById("experiment-control-pattern"),
metric_picker: document.getElementById("experiment-control-metric"),
seed: document.getElementById("experiment-control-seed"),
new_seed: document.getElementById("experiment-control-new-seed"),
play_pause_toggle: document.getElementById("experiment-control-pause-toggle"),
restart: document.getElementById("experiment-control-restart"),
save: document.getElementById("experiment-control-save"),
fullscreen: document.getElementById("experiment-control-fullscreen-toggle"),
invert: document.getElementById("experiment-control-invert"),
show_points: document.getElementById("experiment-control-show-points")
}
Object.keys(sliders).forEach(name => {
let id = name.replaceAll('_', '-')
sliders[name].control = document.getElementById(`experiment-control-${id}`)
sliders[name].label = document.getElementById(`experiment-label-${id}`)
})
//
// Control Handling
//
function setupControls() {
Object.values(sliders).forEach(slider => {
[slider.control.min, slider.control.max, slider.control.step] = slider.range
slider.control.value = slider.value()
slider.label.textContent = slider.value()
})
let fill = (picker, options, selected) => {
Object.entries(options).forEach(([key, option]) => picker.add(new Option(option.label, key, false, key === selected)))
}
fill(controls.color_scheme_picker, color_sets, color_scheme)
fill(controls.pattern_picker, patterns, pattern)
fill(controls.metric_picker, metrics, metric)
controls.seed.value = seed
controls.invert.checked = invert
controls.show_points.checked = show_points
updatePlayPauseIcon()
updateFullscreenIcon()
}
// Both toggle buttons hold two icons and show the one for what a click
// will do next, read from the actual state rather than from counting
// clicks, so leaving fullscreen with the Escape key keeps the icon right.
function showIcon(button, name) {
button.querySelectorAll('svg').forEach(icon => {
icon.classList.toggle('hidden', !icon.classList.contains(`icon-${name}`))
})
}
function updatePlayPauseIcon() {
showIcon(controls.play_pause_toggle, sketch.isLooping() ? 'pause' : 'play')
}
function updateFullscreenIcon() {
showIcon(controls.fullscreen, document.fullscreenElement ? 'compress' : 'expand')
}
// While paused nothing redraws by itself, so any change has to ask for it
function refresh() {
if (!sketch.isLooping()) sketch.redraw()
}
function installControlHandlers() {
controls.play_pause_toggle.addEventListener("click", () => {
sketch.isLooping() ? sketch.noLoop() : sketch.loop()
updatePlayPauseIcon()
})
controls.restart.addEventListener("click", restart)
controls.color_scheme_picker.addEventListener("change", event => { color_scheme = event.target.value; refresh() })
controls.pattern_picker.addEventListener("change", event => { pattern = event.target.value; refresh() })
controls.metric_picker.addEventListener("change", event => { metric = event.target.value; refresh() })
Object.values(sliders).forEach(slider => {
slider.control.addEventListener("input", event => {
slider.label.textContent = event.target.value
slider.update(parseFloat(event.target.value))
refresh()
})
})
// Seed. Typing one in brings those points back, the button rolls new ones
controls.seed.addEventListener("change", event => {
seed = parseInt(event.target.value) || 0
controls.seed.value = seed
restart()
})
controls.new_seed.addEventListener("click", () => {
seed = Math.floor(Math.random() * 1000000)
controls.seed.value = seed
restart()
})
controls.invert.addEventListener("change", event => { invert = event.target.checked; refresh() })
controls.show_points.addEventListener("change", event => { show_points = event.target.checked; refresh() })
controls.save.addEventListener("click", () => {
sketch.save(canvas_el, `worley_noise_${pattern}_${metric}_${color_scheme}_seed${seed}_${cell_size}_${Math.floor(Date.now() / 1000)}`, 'png')
})
controls.fullscreen.addEventListener("click", () => {
sketch.fullscreen(!document.fullscreenElement)
})
// p5's fullscreen() puts <html> in fullscreen, not #sketch-holder, and the
// resize event doesn't reliably wait for the CSS transition that grows
// the holder, so resize once the change has actually settled.
document.addEventListener('fullscreenchange', () => {
updateFullscreenIcon()
sketch.windowResized()
})
}
//
// P5.js touchpoints
//
sketch.setup = () => {
canvas_el = sketch.createCanvas(container.clientWidth, container.clientHeight)
canvas_el.parent(container)
// Start on the scheme that matches the theme the site is being read in
color_scheme = document.documentElement.classList.contains('dark') ? 'site_dark' : 'site_light'
buildPalettes()
// The points start drifting straight away, unless the reader has asked
// their system for less motion
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) sketch.noLoop()
setupControls()
installControlHandlers()
placePoints()
}
sketch.windowResized = () => {
sketch.resizeCanvas(container.clientWidth, container.clientHeight)
placePoints()
refresh()
}
sketch.draw = () => {
// Time only moves while playing, so a redraw asked for by a control
// while paused shows the same moment, just drawn differently
if (sketch.isLooping()) time += speed
movePoints()
let cols = Math.ceil(sketch.width / pixel_size)
let rows = Math.ceil(sketch.height / pixel_size)
if (!noise_image || noise_image.width !== cols || noise_image.height !== rows) {
noise_image = sketch.createImage(cols, rows)
}
let distance = metrics[metric].distance
let current = patterns[pattern]
let palette = palettes[color_scheme]
noise_image.loadPixels()
let pixels = noise_image.pixels
for (let y = 0; y < rows; y++) {
let py = (y + 0.5) * pixel_size
let cell_y = Math.floor(py / cell_size)
for (let x = 0; x < cols; x++) {
let px = (x + 0.5) * pixel_size
let cell_x = Math.floor(px / cell_size)
// The three smallest distances, kept in order as the neighbouring
// cells' points are checked, rather than collecting them all and
// sorting them for every pixel
let f1 = Infinity, f2 = Infinity, f3 = Infinity
for (let i = cell_x - SEARCH; i <= cell_x + SEARCH; i++) {
if (i < 0 || i >= grid_cols) continue
for (let j = cell_y - SEARCH; j <= cell_y + SEARCH; j++) {
if (j < 0 || j >= grid_rows) continue
let point = points[i * grid_rows + j]
let d = distance(px - point.x, py - point.y) / cell_size
if (d < f1) { f3 = f2; f2 = f1; f1 = d }
else if (d < f2) { f3 = f2; f2 = d }
else if (d < f3) { f3 = d }
}
}
let index = (x + y * cols) * 4
if (current.rgb) {
// Oily: each distance drives one colour channel, near is bright
pixels[index] = shade(f1, invert)
pixels[index + 1] = shade(f2 / 1.4, invert)
pixels[index + 2] = shade(f3 / 1.6, invert)
} else {
let value = Math.min(Math.max(current.value(f1, f2, f3), 0), 1)
if (invert) value = 1 - value
let entry = Math.round(value * (SHADES - 1)) * 3
pixels[index] = palette[entry]
pixels[index + 1] = palette[entry + 1]
pixels[index + 2] = palette[entry + 2]
}
pixels[index + 3] = 255
}
}
noise_image.updatePixels()
sketch.noSmooth()
sketch.image(noise_image, 0, 0, cols * pixel_size, rows * pixel_size)
if (show_points) drawPoints()
}
//
// The points
//
// One point per grid cell, each with its own random starting place and
// its own speeds round the cell, all from the seed
function placePoints() {
sketch.randomSeed(seed)
grid_cols = Math.ceil(sketch.width / cell_size)
grid_rows = Math.ceil(sketch.height / cell_size)
points = []
for (let i = 0; i < grid_cols; i++) {
for (let j = 0; j < grid_rows; j++) {
points.push({
cell_x: i * cell_size,
cell_y: j * cell_size,
phase_x: sketch.random(Math.PI * 2),
phase_y: sketch.random(Math.PI * 2),
speed_x: sketch.random(0.5, 1.5) * (sketch.random() < 0.5 ? -1 : 1),
speed_y: sketch.random(0.5, 1.5) * (sketch.random() < 0.5 ? -1 : 1),
x: 0,
y: 0
})
}
}
movePoints()
}
// Each point loops around inside its cell, never leaving it, on a path
// made of two waves at different speeds so it never quite repeats
function movePoints() {
points.forEach(point => {
point.x = point.cell_x + cell_size * (0.5 + 0.4 * Math.sin(point.phase_x + time * point.speed_x))
point.y = point.cell_y + cell_size * (0.5 + 0.4 * Math.cos(point.phase_y + time * point.speed_y))
})
}
function drawPoints() {
sketch.push()
sketch.noStroke()
sketch.fill(color_scheme === 'site_light' ? '#0a0a0a' : '#ffffff')
points.forEach(point => sketch.circle(point.x, point.y, 5))
sketch.pop()
}
//
// Colour
//
// A distance as a 0..255 channel value, bright when near a point
function shade(value, inverted) {
let level = Math.min(Math.max(value, 0), 1)
return Math.round((inverted ? level : 1 - level) * 255)
}
function buildPalettes() {
Object.entries(color_sets).forEach(([key, scheme]) => {
let palette = new Uint8ClampedArray(SHADES * 3)
for (let i = 0; i < SHADES; i++) {
let color = blend(scheme.stops, i / (SHADES - 1))
palette[i * 3] = sketch.red(color)
palette[i * 3 + 1] = sketch.green(color)
palette[i * 3 + 2] = sketch.blue(color)
}
palettes[key] = palette
})
}
// The colour `position` (0 to 1) of the way through a list of stops
function blend(stops, position) {
let scaled = position * (stops.length - 1)
let i = Math.min(Math.floor(scaled), stops.length - 2)
return sketch.lerpColor(sketch.color(stops[i]), sketch.color(stops[i + 1]), scaled - i)
}
// Back to the very start of the current seed
function restart() {
time = 0
placePoints()
refresh()
}
}
// Wait for everything to load
if (document.readyState === 'complete') {
new p5(experiment)
} else {
window.addEventListener('load', () => new p5(experiment))
}