noise
Perlin Noise - 2D Map
- Published
- 2020-12-06
Perlin Noise is a kind of algorithmic random value generator that, unlike pure random methods where each value is unrelated to the previous or next, generates values in a way that whenever you look at one particular value, you know the adjecent values are not radically far of.
I highly recommend this series by Daniel Shiffman of The Coding Train on Perlin Noise for some high energy, high silliness but super informative information on Perlin Noise.
In fact - and without surprise - it was mostly the Coding Train that nudged me to get off my ass and start these experiments (done and redone by thousands of people throughout the internet).
In this particular exercise I’m mapping Perlin Noise onto a 2D space, so effectively you’re seeing the noise values generated as if we’re looking top down onto a surface. What you’re seeing is a highly detailed rendition of the perlin noise values in 2D , but if you click on the image I’ll start to iterate those values, as the rendering is slow (and until I know how to improve things) I’m evaluating and lowering resolution to try and not kill your computer :)
The code is shown bellow, it is literally the code that generates whatever image you’re seeing and I’ll try to work out more interesting experiments, so come back now and then.
Update, October 2026
Six years on, I came back to this with some help from Claude and finally found out why it was so slow. Part of it was a bug: p5 already scales everything for high density screens (any Mac or phone), and I was scaling again on top of that, so the map came out twice the size it should have been. You only ever saw its top left corner, and three quarters of the work was happening outside the canvas. The other part was drawing every single pixel as its own rectangle, hundreds of thousands of them per frame when paused at full detail.
Now each cell is computed once, written straight into a small image (one pixel per cell), and that image is stretched over the canvas. That’s around 5 milliseconds a frame at the default settings, so all my “lower the resolution until it stops hurting” logic is gone, and it doesn’t need clicking to start any more: there’s a play button.
It also has controls now :) Pixel size, noise scale, how many octaves of detail and how rough they are, how fast it evolves, a seed, and a few colour schemes, including the original greyscale. The one I like most is the “Steps” slider, which cuts the gradient into flat bands, and with the Topographic scheme it turns into a map:
That’s the same idea as the Marching Squares topographic map, except here the bands come straight from the values rather than from tracing the lines between them.
Source — sketch.js
'use strict'
// Perlin noise mapped onto a 2D surface: every cell of the canvas is
// coloured by the noise value at its position, as if looking straight down
// at a landscape where the value is the height. Time is the third noise
// dimension, so while playing the landscape slowly reshapes itself.
// 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 pixel_size = 3 // Size of one sampled cell, in pixels: 1 is every pixel
let noise_scale = 0.004 // Noise units per pixel: small is broad shapes, big is fine grain
let detail = 6 // Noise octaves: each adds a finer, fainter layer on top
let roughness = 0.5 // How strong each octave is compared to the one before it
let steps = 0 // Quantise the values into this many bands, zero for a smooth gradient
let evolution_speed = 0.004 // How far the third noise dimension moves every frame, zero freezes it
let smooth = false // Blend between cells instead of drawing crisp blocks
let noise_z = 0 // Time
// The same seed gives the same landscape
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,
// "pixel_size" to #experiment-control-pixel-size and its label
// #experiment-label-pixel-size
let sliders = {
pixel_size: { range: [1, 20, 1], value: () => pixel_size, update: value => { pixel_size = value } },
noise_scale: { range: [0.001, 0.02, 0.001], value: () => noise_scale, update: value => { noise_scale = value } },
detail: { range: [1, 8, 1], value: () => detail, update: value => { detail = value; sketch.noiseDetail(detail, roughness) } },
roughness: { range: [0.1, 0.9, 0.05], value: () => roughness, update: value => { roughness = value; sketch.noiseDetail(detail, roughness) } },
steps: { range: [0, 20, 1], value: () => steps, update: value => { steps = value } },
evolution_speed: { range: [0, 0.02, 0.001], value: () => evolution_speed, update: value => { evolution_speed = value } }
}
// Color Schemes
//
// `stops` are the colours the map runs through from the lowest value to
// the highest; any number of stops, blended evenly. "Greyscale" is the
// original look, the two "site" schemes use the site's own palette.
let color_scheme
let color_sets = {
greyscale: {
label: "Greyscale",
stops: ["#000000", "#ffffff"]
},
site_dark: {
label: "Site Dark",
stops: ["#0a0a0a", "#2e2e2e", "#8a3a06", "#ff6600", "#ffd9b8"]
},
site_light: {
label: "Site Light",
stops: ["#ffffff", "#f0f0f0", "#ffc49c", "#ff6600", "#b84900"]
},
topographic: {
label: "Topographic",
stops: ["#1d4e89", "#3f7cac", "#9cc3d5", "#e4dca4", "#b5d3a0", "#6a9a5b", "#8a6a4a", "#b98a6a", "#f4f1ea"]
},
heat: {
label: "Heat",
stops: ["#000000", "#5c0a0a", "#c2290a", "#ff6600", "#ffd23f", "#ffffff"]
}
}
// Each scheme's colours, worked out once as a lookup table of 256 RGB
// triplets, so colouring a cell is an array read rather than a blend
const SHADES = 256
let palettes = {}
// With more octaves p5's noise() clusters more tightly around 0.5, and
// rarely reaches either end of 0..1. Values are stretched from this range
// to fill the palette, so the colours don't all bunch up in the middle.
const NOISE_LOW = 0.2
const NOISE_HIGH = 0.8
// The map, one pixel per cell, drawn scaled up to fill the canvas
let map_image
// Controls
let controls = {
color_scheme_picker: document.getElementById("experiment-control-color-scheme"),
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"),
smooth: document.getElementById("experiment-control-smooth")
}
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()
})
Object.entries(color_sets).forEach(([key, scheme]) => {
controls.color_scheme_picker.add(new Option(scheme.label, key, false, key === color_scheme))
})
controls.seed.value = seed
controls.smooth.checked = smooth
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()
})
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 that landscape back, the button rolls a new one
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.smooth.addEventListener("change", event => {
smooth = event.target.checked
refresh()
})
controls.save.addEventListener("click", () => {
sketch.save(canvas_el, `perlin_noise_2d_${color_scheme}_seed${seed}_${pixel_size}_${noise_scale}_${detail}_${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()
sketch.noLoop() // Show a still map until play is pressed (p5 still draws it once)
setupControls()
installControlHandlers()
resetLandscape()
}
sketch.windowResized = () => {
sketch.resizeCanvas(container.clientWidth, container.clientHeight)
refresh()
}
sketch.draw = () => {
// Time only moves while playing, so a redraw asked for by a control
// while paused shows the same landscape, just drawn differently
if (sketch.isLooping()) noise_z += evolution_speed
let cols = Math.ceil(sketch.width / pixel_size)
let rows = Math.ceil(sketch.height / pixel_size)
if (!map_image || map_image.width !== cols || map_image.height !== rows) {
map_image = sketch.createImage(cols, rows)
}
let palette = palettes[color_scheme]
map_image.loadPixels()
let pixels = map_image.pixels
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
// Sampled at the middle of the cell, in canvas pixels times
// noise_scale, so a bigger pixel size shows the same landscape
// more coarsely rather than zooming out of it
let value = sketch.noise((x + 0.5) * pixel_size * noise_scale, (y + 0.5) * pixel_size * noise_scale, noise_z)
let level = Math.min(Math.max((value - NOISE_LOW) / (NOISE_HIGH - NOISE_LOW), 0), 1)
// Steps turn the gradient into flat bands, like contour shading
if (steps > 0) level = Math.min(Math.floor(level * steps), steps - 1) / Math.max(steps - 1, 1)
let shade = Math.round(level * (SHADES - 1)) * 3
let index = (x + y * cols) * 4
pixels[index] = palette[shade]
pixels[index + 1] = palette[shade + 1]
pixels[index + 2] = palette[shade + 2]
pixels[index + 3] = 255
}
}
map_image.updatePixels()
// One pixel per cell, stretched over the canvas: crisp blocks, or
// blended between cells when smoothing is on
smooth ? sketch.smooth() : sketch.noSmooth()
sketch.image(map_image, 0, 0, cols * pixel_size, rows * pixel_size)
}
//
// Colour
//
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 resetLandscape() {
sketch.noiseSeed(seed)
sketch.noiseDetail(detail, roughness)
noise_z = 0
}
function restart() {
resetLandscape()
refresh()
}
}
// Wait for everything to load
if (document.readyState === 'complete') {
new p5(experiment)
} else {
window.addEventListener('load', () => new p5(experiment))
}