noise
Perlin Noise - Linear Mapping
- 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 line, traveling forward along the x-axis of the Perlin generated noise.
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
Going back through these with Claude’s help, one word kept coming up in the other experiments: octaves. The “Detail” slider in Live Background, and in the 2D map, is just how many of them get added together. So this one, the simplest of the lot, now shows what that actually means.
The noise isn’t one curve, it’s several stacked on top of each other. The first is big and slow, then the same kind of curve again, twice as wiggly and (by default) half as tall, then again, and again. Add them up and you get a line that has big hills and small bumps, which is why it looks natural rather than like a smooth wave. With “Show layers” on, each one gets its own lane under the final line:
You can match the big shapes in the orange line to the first layer, and the small jitter to the last ones. The sliders let you change how many layers there are and how fast they shrink (Roughness: turn it up and the small bumps take over), along with the noise scale, scroll speed and a seed.
There was also a small bug, the same kind of high density screen mix-up as in the 2D map: it was drawing twice as many points as the canvas is wide, so half of them were always off the right hand edge.
Source — sketch.js
'use strict'
// One dimensional Perlin noise drawn as a line: each point's height is the
// noise value at its position, and the line scrolls by moving where along
// the noise it starts.
//
// p5 builds its noise in layers ("octaves"): the same smooth curve again and
// again, each time twice as wiggly and, by default, half as tall, all added
// together. "Show layers" draws each of those layers on its own, in a lane
// of its own under the final line.
// 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 noise_scale = 0.008 // Noise units per pixel: small is gentle hills, big is jagged
let detail = 4 // Noise octaves: how many layers are added together
let roughness = 0.5 // How tall each layer is compared to the one before it
let speed = 1 // How many pixels the line scrolls every frame
let show_layers = true
let offset = 0 // How far along the noise the left edge of the canvas is, in pixels
// The same seed gives the same line
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,
// "noise_scale" to #experiment-control-noise-scale and its label
// #experiment-label-noise-scale
let sliders = {
noise_scale: { range: [0.001, 0.05, 0.001], value: () => noise_scale, update: value => { noise_scale = value } },
detail: { range: [1, 8, 1], value: () => detail, update: value => { detail = value } },
roughness: { range: [0.1, 0.9, 0.05], value: () => roughness, update: value => { roughness = value } },
speed: { range: [0, 10, 0.5], value: () => speed, update: value => { speed = value } }
}
// Color Schemes
//
// `layers` are the colours of the octaves, from the first (broadest) to
// the last (finest), blended evenly across however many there are.
// "Classic" is the 2020 original.
let color_scheme
let color_sets = {
site_dark: {
label: "Site Dark",
background: "#0a0a0a",
line: "#ff6600",
layers: ["#ffffff", "#555555"]
},
site_light: {
label: "Site Light",
background: "#ffffff",
line: "#b84900",
layers: ["#0a0a0a", "#b0b0b0"]
},
classic: {
label: "Classic (2020)",
background: "#282828",
line: "#ffffff",
layers: ["#8a8a8a", "#3c3c3c"]
}
}
// 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"),
show_layers: document.getElementById("experiment-control-show-layers")
}
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.show_layers.checked = show_layers
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 line 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.show_layers.addEventListener("change", event => {
show_layers = event.target.checked
refresh()
})
controls.save.addEventListener("click", () => {
sketch.save(canvas_el, `perlin_noise_linear_${color_scheme}_seed${seed}_${detail}_${roughness}_${noise_scale}_${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'
// It scrolls by itself, unless the reader has asked their system for
// less motion
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) sketch.noLoop()
setupControls()
installControlHandlers()
sketch.noiseSeed(seed)
}
sketch.windowResized = () => {
sketch.resizeCanvas(container.clientWidth, container.clientHeight)
refresh()
}
sketch.draw = () => {
// Only moves while playing, so a redraw asked for by a control while
// paused shows the same stretch of line, just drawn differently
if (sketch.isLooping()) offset += speed
let colors = color_sets[color_scheme]
sketch.background(colors.background)
// With the layers showing, the line takes the top half of the canvas
// and the layers share the bottom
let line_area = show_layers ? sketch.height * 0.5 : sketch.height
drawLine(colors, 0, line_area)
if (show_layers) drawLayers(colors, line_area, sketch.height - line_area)
}
//
// The line and its layers
//
// p5 starts the first layer at half height and multiplies each one after
// by the roughness, so with the default 0.5 they go 1/2, 1/4, 1/8... Added
// up, they can reach this high at most, which is what the line is scaled by
// to always fill its space whatever the settings.
function totalAmplitude() {
let total = 0
for (let k = 0; k < detail; k++) total += 0.5 * Math.pow(roughness, k)
return total
}
// Where along the noise a pixel column is. One point per pixel: drawing
// more than the canvas is wide (the 2020 version drew twice as many on
// high density screens) only puts them off the edge.
function position(x) {
return (offset + x) * noise_scale
}
// The final line, between `top` and top + height: the sum of all the
// layers, which is just what noise() returns with noiseDetail set to that
// many layers
function drawLine(colors, top, height) {
let margin = height * 0.1
let total = totalAmplitude()
sketch.noiseDetail(detail, roughness)
sketch.push()
sketch.noFill()
sketch.stroke(colors.line)
sketch.strokeWeight(2)
sketch.beginShape()
for (let x = 0; x <= sketch.width; x++) {
let value = sketch.noise(position(x)) / total
sketch.vertex(x, sketch.map(value, 0, 1, top + height - margin, top + margin))
}
sketch.endShape()
sketch.pop()
}
// Each layer on its own, one lane each, broadest first. A layer is one
// octave of noise (noiseDetail of 1, which p5 returns at half height,
// hence the * 2) read at 2^k times the position, so each one is twice as
// wiggly as the one above it, and drawn at its real height compared to
// the first, so you can see them shrink as the roughness takes effect.
// A single octave rarely strays far from the middle, so the first layer
// is stretched to fill most of its lane.
function drawLayers(colors, top, height) {
let lane = height / detail
sketch.noiseDetail(1, 0.5)
sketch.push()
sketch.noFill()
sketch.strokeWeight(1.5)
for (let k = 0; k < detail; k++) {
let scale = Math.pow(roughness, k)
let frequency = Math.pow(2, k)
let middle = top + lane * (k + 0.5)
sketch.stroke(blend(colors.layers, detail === 1 ? 0 : k / (detail - 1)))
sketch.beginShape()
for (let x = 0; x <= sketch.width; x++) {
let layer = sketch.noise(position(x) * frequency) * 2
sketch.vertex(x, middle - (layer - 0.5) * scale * lane * 1.5)
}
sketch.endShape()
}
sketch.pop()
}
// The colour `position` (0 to 1) of the way through a list of stops
function blend(stops, position) {
return sketch.lerpColor(sketch.color(stops[0]), sketch.color(stops[stops.length - 1]), position)
}
// Back to the very start of the current seed
function restart() {
sketch.noiseSeed(seed)
offset = 0
refresh()
}
}
// Wait for everything to load
if (document.readyState === 'complete') {
new p5(experiment)
} else {
window.addEventListener('load', () => new p5(experiment))
}