Perlin noise

Perlin noise explained: build it step by step in JavaScript

Learn how Perlin noise works by building it from scratch in JavaScript, with a live demo for every step. Then use it to make hills for a side-scroller, island maps, cloud and marble textures, and flow field art.

Every line in the demo below gets its direction from the same Perlin noise, so neighboring lines flow in almost the same direction. Click or tap the demo to start over with new noise:

By the end of this tutorial, you'll know how to build this yourself.

What is Perlin noise?

Perlin noise is a function that turns a position into a number. Positions that are close together get numbers that are close together, so the values change smoothly as you move along. That's why it's often described as smooth randomness.

Math.random() is different. It gives you a new number every time you call it, and each number has nothing to do with the one before. That's perfect for a dice roll, but a landscape built from Math.random() looks like a bar chart gone wild. The tutorial about random numbers in JavaScript covers everything you can do with it.

In the demo below, the top graph gets a new value from Math.random() eight times per second, shown by a red dot. The bottom graph, with a blue dot, uses the time as its position in the Perlin noise, and moves that position forward a little every frame:

The red dot jumps all over the place, while the blue dot drifts up and down. Both are unpredictable, but only the blue one moves like something natural, such as a leaf in the wind.

Perlin noise isn't random in the way Math.random() is. Give it the same position, and you get the same number back, every time. The randomness comes from a list of random numbers that you make once, at the start. You'll see how that works further down this page.

Ken Perlin came up with it in 1983, after working on the computer graphics for the movie Tron. He wanted textures that looked less like they came out of a machine. In 1997, he won an Academy Award for Technical Achievement for it. Today, games and movies use Perlin noise for terrain, clouds, fire and water, and for movement that looks alive.

Start with value noise in one dimension

Before you build Perlin noise, start with a simpler kind of smooth noise: value noise. Work in one dimension first, like a line on a graph, where the position is a single number x.

Give every whole number on the line a random value. The number 0 gets one random value, 1 gets another one, and so on. For a position in between, like 2.4, look up the values of 2 and 3, and blend them. The closer x gets to 3, the closer the result gets to the value of 3:

const values = [];

for (let i = 0; i < 256; i++) {
    values.push(Math.random() * 2 - 1);
}

// Blend from a to b: t = 0 gives a, and t = 1 gives b
function lerp(a, b, t) {
    return a + (b - a) * t;
}

function valueNoise1D(x) {
    let x0 = Math.floor(x);
    let t = x - x0;
    let a = values[x0 & 255];
    let b = values[(x0 + 1) & 255];
    return lerp(a, b, t);
}

values holds 256 random numbers between -1 and 1. In valueNoise1D(), Math.floor() gives the whole number to the left of x, and t is how far x is past it, from 0 to 1. lerp() is short for linear interpolation: it moves in a straight line from a to b.

The & 255 keeps the index between 0 and 255. It gives the remainder after dividing by 256, a trick that only works because 256 is a power of 2. So the 256 values repeat along the line, but you'd need a very long line to notice. Unlike %, & 255 also works for negative numbers: the index never goes below 0.

With lerp() alone, the line makes a sharp corner at every whole number. To round those corners off, don't blend with t itself, but with a fade curve. It starts slow, speeds up in the middle and slows down again at the end, just like an ease-in-out curve in our animation tool for easing functions:

function fade(t) {
    return t * t * t * (t * (t * 6 - 15) + 10);
}

This is 6t5 - 15t4 + 10t3, written so it needs fewer multiplications. At t = 0 and t = 1, the curve is completely flat, so neighboring pieces meet without a corner. In valueNoise1D(), replace lerp(a, b, t) with lerp(a, b, fade(t)). Ken Perlin picked this curve in 2002, in a paper called Improving Noise.

Try it in the demo below. Drag a dot up or down, and switch between Linear and Smooth:

Interpolation

Value noise works, but it has a weakness. The highest and lowest points always land on whole numbers. In 2D, that makes value noise look a bit blocky. Perlin noise fixes this with one small change.

Use gradients to turn value noise into Perlin noise

Instead of a random value, Perlin noise gives every whole number a random slope, also called a gradient. At the whole number itself, the noise is always 0. From there, it goes up or down with that slope.

Between two whole numbers, you get two straight lines. Each one goes through 0 at its own whole number, with that number's slope. Blend the two lines with the fade curve, just like before:

const slopes = [];

for (let i = 0; i < 256; i++) {
    slopes.push(Math.random() * 2 - 1);
}

function perlin1D(x) {
    let x0 = Math.floor(x);
    let t = x - x0;
    // The lines through the whole numbers on either side
    let a = slopes[x0 & 255] * t;
    let b = slopes[(x0 + 1) & 255] * (t - 1);
    return lerp(a, b, fade(t));
}

Line a is the slope at the left whole number times the offset from that number, which is t. Line b is the slope at the right whole number times the offset from that one, which is t - 1. That offset is negative, because x lies to the left of the right whole number. At t = 0, line a gives 0, and at t = 1, line b gives 0. In between, fade() blends smoothly from one line into the other.

In the demo below, the short blue lines are the slopes. Drag the end of a slope to tilt it. Switch to Slopes to see the two straight lines that get blended: blue for the line through the left whole number, and red for the line through the right one:

Show

The curve goes through 0 at every whole number, but the hills and valleys now fall in between, each at a different spot. That's what makes Perlin noise look more natural than value noise.

With slopes between -1 and 1, perlin1D() stays between -0.5 and 0.5. It can only get that far from 0 halfway between two whole numbers, and only when both lines are at 0.5 there, or both at -0.5.

Make 2D noise with a grid of arrows

For an image, a map or a cloud, you need noise in two dimensions: a value for every x and y. The idea stays the same, but the whole numbers become the corners of a grid of squares. Every corner gets a gradient, which in 2D is an arrow: a direction, with a length of 1.

For a point (x, y), find the square it's in. Then, for each of the four corners of that square, take these steps:

  • Get the corner's arrow - Each corner has its own random direction.
  • Get the offset - That's the arrow from the corner to the point: x minus the x of the corner, and y minus the y of the corner.
  • Take the dot product - Multiply the x of the arrow by the x of the offset, do the same for y, and add up the results.

The dot product tells you how far the point lies in the direction of the corner's arrow. If the point lies in front of the arrow, the dot product is positive. Behind the arrow, it's negative, and at a right angle to it, it's 0. The tutorial about collision detection and physics uses the dot product too, to find the speed of a collision.

The four corners give you four dot products. To turn them into one number, take these steps:

  • Blend the top two - Use fade() of how far across the square the point is.
  • Blend the bottom two - Do it the same way.
  • Blend those two results - Use fade() of how far down the square the point is.

The result is Perlin noise. Just like in 1D, the noise is 0 at every corner, because the offset there is 0.

Move your mouse or finger over the grid below. The red dot is the point, the dashed lines go from the four corners to the point, and the numbers are the four dot products. Switch to Noise to see the result for every point on the canvas:

Show

Near a corner, the noise follows that corner's arrow: it's light in front of the arrow, where the dot product is positive, and dark behind it.

So where do the arrows come from? You could store a random arrow for every corner, but you'd need a huge grid of them, and the grid never ends. Perlin noise uses a trick instead: a single list with the numbers 0 to 255 in a random order, called a permutation table. Look up the x of the corner in the list, add the y of the corner to the result, and look that up in the list again. That gives every corner a number from 0 to 255, and it's always the same number for the same corner.

That number picks one of 256 arrows, spread evenly around a circle. createNoise() makes the list of arrows and the permutation table, and shuffles the table with the Fisher-Yates shuffle. That shuffle walks through the list backward, and swaps each number with the number at a random spot before it, or with itself. Call createNoise() once, at the start of your script:

let perm = [];
let gradients = [];

function createNoise() {
    perm = [];
    gradients = [];
    for (let i = 0; i < 256; i++) {
        perm.push(i);
        // 256 arrows with a length of 1, all around the circle
        let angle = i / 256 * Math.PI * 2;
        gradients.push({x: Math.cos(angle), y: Math.sin(angle)});
    }
    shuffle(perm);
}

function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        let temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

With the two lists in place, here's Perlin noise in 2D:

function getGradient(ix, iy) {
    let index = perm[(perm[ix & 255] + iy) & 255];
    return gradients[index];
}

// The dot product of the corner's arrow and the offset to (x, y)
function cornerValue(ix, iy, x, y) {
    let gradient = getGradient(ix, iy);
    let dx = x - ix;
    let dy = y - iy;
    return gradient.x * dx + gradient.y * dy;
}

function perlin2D(x, y) {
    let x0 = Math.floor(x);
    let y0 = Math.floor(y);
    let u = fade(x - x0);
    let v = fade(y - y0);
    let topLeft = cornerValue(x0, y0, x, y);
    let topRight = cornerValue(x0 + 1, y0, x, y);
    let bottomLeft = cornerValue(x0, y0 + 1, x, y);
    let bottomRight = cornerValue(x0 + 1, y0 + 1, x, y);
    let top = lerp(topLeft, topRight, u);
    let bottom = lerp(bottomLeft, bottomRight, u);
    return lerp(top, bottom, v);
}

In getGradient() and cornerValue(), ix and iy are the corner's whole-number coordinates. In cornerValue(), x and y are the coordinates of the point. perlin2D() finds the top-left corner of the square with Math.floor(), just like perlin1D(). u is fade() of how far across the square the point is, and v is fade() of how far down.

Draw the noise on the canvas

Now that you have a value for every x and y, you can turn every pixel of the canvas into a shade of gray. In 2D, perlin2D() gives values between about -0.7 and 0.7. Turn that into a number from 0 for black to 255 for white, and write it into an ImageData object:

function drawNoise(frequency) {
    let image = context.createImageData(canvas.width, canvas.height);
    for (let y = 0; y < canvas.height; y++) {
        for (let x = 0; x < canvas.width; x++) {
            let value = perlin2D(x * frequency, y * frequency);
            let gray = (value / 0.7 + 1) / 2 * 255;
            let i = (y * canvas.width + x) * 4;
            image.data[i] = gray;
            image.data[i + 1] = gray;
            image.data[i + 2] = gray;
            image.data[i + 3] = 255;
        }
    }
    context.putImageData(image, 0, 0);
}

Here's what the lines inside the loops do:

  • (value / 0.7 + 1) / 2 * 255 - Turns the noise into a gray value from 0 to 255. Dividing by 0.7 gives about -1 to 1, adding 1 makes that 0 to 2, and the rest makes it 0 to 255.
  • (y * canvas.width + x) * 4 - Finds where the pixel starts in image.data. The pixels are stored row by row, with four numbers for each: red, green, blue and alpha.
  • image.data[i + 3] = 255 - Sets the alpha, so the pixel is fully opaque.

A gray pixel has the same number for red, green and blue. The array in image.data only holds whole numbers from 0 to 255, so it rounds the gray value for you and clamps it to that range. The tutorial about Voronoi diagrams explains ImageData in more detail.

Why multiply x and y by frequency? Without it, every pixel would land exactly on a corner of the grid, where the noise is always 0, and the whole canvas would be the same gray. With a frequency of 0.02, each grid square is 50 pixels wide, because 1 / 0.02 = 50. So a higher frequency gives you smaller shapes, not bigger ones: more squares fit on the canvas.

Every time you call createNoise(), the shuffle gives a new permutation table, so you get different noise. To get the same noise every time, shuffle with a random number generator that takes a seed: a starting number, like 1234. The tutorial about random numbers in JavaScript has one: Mulberry32, a small generator by Tommy Ettinger. You'll also find mulberry32() in the example code at the end of this page. Pass the seed to mulberry32(), and use the function it gives you instead of Math.random():

function createNoise(seed) {
    let random = mulberry32(seed);
    // ...
    shuffle(perm, random);
}

function shuffle(array, random) {
    for (let i = array.length - 1; i > 0; i--) {
        let j = Math.floor(random() * (i + 1));
        // ...
    }
}

Pick a frequency in the demo below, and click New seed for different noise. The seed and the time it took to draw are in the corner of the demo:

frequency

The canvas in the demo is 750 by 400 pixels, so drawing it means 300,000 calls to perlin2D(), one for each pixel. On a laptop, that takes about 5 to 15 milliseconds, and a lot longer on a phone. That's fine for a picture you draw once, but redrawing it every frame uses up most of the time you have for one frame, and a phone can't keep up. You'll find a way around that in the section about textures.

Add detail with octaves

One layer of Perlin noise is smooth, like rolling hills. Real terrain also has rocks on the hills, and pebbles on the rocks. To get that, add up several layers of noise. Each layer gets double the frequency, so its shapes are half the size. It also gets half the strength, so it adds detail without changing the big shapes.

A layer is called an octave, after the octave in music: a note one octave higher has double the frequency too. The result is called fractal noise, or fractional Brownian motion, often shortened to fBm:

function fractalNoise(x, y, octaves, persistence) {
    let total = 0;
    let frequency = 1;
    let amplitude = 1;
    let maxTotal = 0;
    for (let i = 0; i < octaves; i++) {
        let value = perlin2D(x * frequency, y * frequency);
        total += value * amplitude;
        maxTotal += amplitude;
        frequency *= 2;
        amplitude *= persistence;
    }
    return total / maxTotal;
}

persistence sets how strong each octave is compared to the one before: with 0.5, each octave counts half as much. maxTotal is the total strength of all octaves, and dividing by it keeps the result within the range of a single layer. The number the frequency gets multiplied by for each octave is called the lacunarity, and most implementations keep it at 2.

Inside fractalNoise(), frequency starts at 1 and doubles for each octave. You set the frequency for the whole picture when you call it, as in fractalNoise(x * 0.006, y * 0.006, 5, 0.5).

The bottom part of the demo below shows fractal noise in 2D. The top part shows one row of it, along the dashed line: the thin colored lines are the octaves, and the thick line is their sum. Change the number of octaves and the persistence:

Octaves
Persistence

Each octave costs one more call to perlin2D() for every pixel, so 8 octaves are 8 times as much work as 1. With the frequency of 0.006 in the demo, the squares of the first octave are about 167 pixels wide. Those of the eighth octave are less than 2 pixels wide, so more octaves won't add anything you can see.

Use noise for smooth movement and wobbly shapes

Noise isn't only for pictures. Use time as the position, and you get a value that changes smoothly over time. That's great for anything that should move as if it's alive.

For a bee that wanders around, read the noise at the current time for x. For y, read a different part of the noise by adding an offset that ends in .5. perlin1D() is 0 at every whole number. With a whole number like 100, x and y would both be 0 at the same moments, and the bee would fly through the middle every 2 seconds:

let time = 0;

function update(secondsPassed) {
    time += secondsPassed;
    // Two different places in the noise, so x and y move differently
    bee.x = canvas.width / 2 + perlin1D(time * 0.5) * 600;
    bee.y = canvas.height / 2 + perlin1D(time * 0.5 + 100.5) * 330;
}

secondsPassed is the time since the last frame, as explained in the tutorial about the JavaScript game loop. The bee stays within 300 pixels to the left or right of the center, and within 165 pixels above or below it, because perlin1D() stays between -0.5 and 0.5. Multiply time by a number bigger than 0.5 on both lines, and the bee flies faster. The tutorial about steering behaviors has another way to make something wander.

For a blob that changes shape, start with a circle, and push each point on its edge in or out with the noise. Read the noise along a circle too, so the shape has no seam. Then move the circle in the noise over time, and the blob starts to wobble:

function drawBlob(centerX, centerY, radius) {
    context.beginPath();
    for (let i = 0; i < 120; i++) {
        let angle = i / 120 * Math.PI * 2;
        // A circle in the noise, which moves to the right over time
        let nx = Math.cos(angle) * 0.8 + time * 0.25;
        let ny = Math.sin(angle) * 0.8;
        let r = radius * (1 + perlin2D(nx, ny) * 0.9);
        let x = centerX + Math.cos(angle) * r;
        let y = centerY + Math.sin(angle) * r;
        if (i == 0) {
            context.moveTo(x, y);
        } else {
            context.lineTo(x, y);
        }
    }
    context.closePath();
    context.fill();
}

The blob is a path with 120 points, drawn with moveTo() and lineTo(), like the paths in the tutorial about drawing on the canvas. The 0.8 is the radius of the circle in the noise: a bigger circle gives a bumpier blob. The 0.9 sets how far the edge can move in or out.

Why a circle in the noise? If you used perlin1D(angle) instead, the noise at the last point wouldn't match the noise at the first point, and the edge would jump where they meet. On a circle, the noise ends where it started.

A screen shake looks better with noise too. Take a number called trauma, between 0 and 1, that jumps up with every hit and drops back down over time. The tutorial about a 2D game camera combines trauma with Math.random(), so the screen jumps to a new spot every frame. With noise, the screen swings from side to side instead:

// Trauma drops back to 0 in one second
trauma = Math.max(trauma - secondsPassed, 0);
let shake = trauma * trauma;
let shakeX = maxShake * shake * perlin1D(time * 25) * 2;
let shakeY = maxShake * shake * perlin1D(time * 25 + 50.5) * 2;

The * 2 stretches the noise from -0.5 to 0.5 into -1 to 1, the same range as Math.random() * 2 - 1. Adding 50.5 makes y read a different part of the noise, again with an offset that ends in .5. Multiplying time by 25 makes the noise change fast enough for a shake. maxShake is the farthest the screen can move, in pixels. Squaring trauma makes a small hit shake a lot less than a big one.

Add shakeX and shakeY to the position of everything you draw, for example with translate() before you draw the scene.

Here are all three. In Shake, the crates get a hit every 2.5 seconds, and the graph in the corner shows shakeX:

Example

Generate hills for a side-scroller

For a side-scroller, you need the height of the ground at every x. That's 1D noise, with octaves for detail. You don't need a new function for that: fractalNoise() works with 2D noise, and a single row of 2D noise is 1D noise too. Pick a y, and only change x:

function drawHills(cameraX, y, base, hillHeight, color) {
    context.fillStyle = color;
    context.beginPath();
    context.moveTo(0, canvas.height);
    for (let x = 0; x <= canvas.width; x += 5) {
        let value = fractalNoise((x + cameraX) * 0.004, y, 3, 0.4);
        context.lineTo(x, base - value * hillHeight);
    }
    context.lineTo(canvas.width, canvas.height);
    context.closePath();
    context.fill();
}

Every 5 pixels, the path goes to the height of the hills at that spot. Then it closes the shape along the bottom of the canvas, so fill() colors everything under the hills. base is where the ground is on the canvas when the noise is 0, and hillHeight sets how high the hills go. On the canvas, the y-axis points down, so the code subtracts the noise to make the hills go up.

cameraX is how far the world has scrolled. Add it to x, and the hills move to the left as the camera moves to the right. Because the noise never ends, neither do the hills.

For depth, draw three layers from back to front. Each layer reads its own row of the noise, and the rows are 10 apart, so the layers look different. The row numbers end in .3 instead of .5: fractalNoise() doubles the row for each octave, and 0.5 doubled is a whole number. With .3, none of the octaves runs exactly through the corners of the grid, where the noise is 0. Each layer also gets its own base, hill height, color and speed:

drawHills(cameraX * 0.25, 0.3, 170, 240, '#a9c0d0');
drawHills(cameraX * 0.5, 10.3, 250, 180, '#7dbb84');
drawHills(cameraX, 20.3, 330, 120, '#4a8f57');

The layers in the back move slower, which makes them look farther away. This is called parallax scrolling, and the tutorial about a 2D game camera explains it in more detail.

Drag the landscape below to scroll it yourself. Switch to Mountains for hills that are 1.6 times as high, with a lower frequency, 6 octaves and a persistence of 0.55:

Terrain

Make a map with islands

In 2D, you can use the noise as the height of the land, and give each range of heights its own color. Deep water comes at the bottom, then shallow water, sand, grass, forest and rock, and snow at the top:

const terrain = [
    {height: -0.12, color: [38, 84, 150]},     // Deep water
    {height: 0, color: [70, 140, 200]},        // Shallow water
    {height: 0.035, color: [236, 218, 164]},   // Sand
    {height: 0.15, color: [124, 192, 92]},     // Grass
    {height: 0.27, color: [66, 138, 74]},      // Forest
    {height: 0.38, color: [138, 128, 118]},    // Rock
    {height: Infinity, color: [248, 248, 248]} // Snow
];

function getTerrainColor(height) {
    for (let level of terrain) {
        if (height < level.height) {
            return level.color;
        }
    }
}

getTerrainColor() walks through the list from the bottom up, and returns the color of the first level that's higher than the land. For each pixel, write that color into the ImageData, just like the gray values before.

Fractal noise alone gives you land and water all over the canvas. For an island, lower the land toward the edges of the canvas:

function getHeight(x, y) {
    let height = fractalNoise(x * 0.006, y * 0.006, 5, 0.5);
    // Distance from the center: 1 at the middle of each edge
    let dx = x / canvas.width * 2 - 1;
    let dy = y / canvas.height * 2 - 1;
    let distance = Math.sqrt(dx * dx + dy * dy);
    return height + 0.28 - distance * 0.55;
}

In the middle of the canvas, the land goes up by 0.28, so there's more of it. At the middle of each edge, it goes down by 0.27, and almost everything there is water.

Click New map for a different island. Switch to Endless for a map without the island shape. That map keeps scrolling to the left:

Map

In a game, each color can be a type of tile, like grass that's easy to walk on and forest that's slow to get through. The tutorial about pathfinding algorithms shows how to find the shortest path over tiles that take different amounts of time to cross.

If you use a seed, the same seed always gives the same map. That's how many games let players share a world: they share the seed.

Make cloud, marble and wood textures

The same noise can make all kinds of textures. Here are three classics, and how they use the noise:

  • Clouds - Fractal noise sets how much white goes on top of a blue sky. A lower frequency for x than for y stretches the clouds sideways, so they look flatter.
  • Marble - Put the noise inside Math.sin(). The sine makes stripes, and the noise bends them into veins.
  • Wood - The distance to the middle makes rings. Add some noise to bend them, and keep only the part after the decimal point, so every ring starts over.

The functions below make the clouds, the marble and the wood. Each returns a number from 0 to 1, and mixColor() turns that into a mix of two colors:

// Mix two colors: t = 0 gives a, and t = 1 gives b
function mixColor(a, b, t) {
    return [
        lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)
    ];
}

function getCloud(x, y) {
    // A lower frequency for x stretches the clouds sideways
    let value = fractalNoise(x * 0.004, y * 0.008, 6, 0.55);
    // 0 is clear sky, and 1 is a thick cloud
    return Math.min(Math.max((value + 0.05) * 3.5, 0), 1);
}

function getMarble(x, y) {
    let value = fractalNoise(x * 0.004, y * 0.004, 4, 0.5);
    let wave = Math.sin((x + y * 0.5) * 0.015 + value * 10);
    // Dark only where the wave is close to 0
    return Math.pow(1 - Math.abs(wave), 6);
}

function getWood(x, y) {
    // Stretch the rings sideways, so they're long and thin
    let dx = (x - canvas.width / 2) * 0.25;
    let dy = y - canvas.height / 2;
    let rings = Math.sqrt(dx * dx + dy * dy) * 0.06;
    rings += fractalNoise(x * 0.003, y * 0.012, 4, 0.5) * 2.5;
    // The part after the decimal point: from 0 to 1 in every ring
    return Math.pow(rings - Math.floor(rings), 3);
}

In getMarble(), y * 0.5 slants the stripes, and the 10 sets how much the noise bends them.

For clouds, mix a sky blue with white: mixColor([110, 170, 230], [255, 255, 255], getCloud(x, y)). For marble, mix an off-white with a blue-gray: mixColor([246, 245, 242], [120, 124, 140], getMarble(x, y)). For wood, mix a light brown with a darker one.

The clouds in the demo below drift, so they need a new picture every frame. With 6 octaves, computing the noise for every pixel every frame takes too long, even on a laptop. But noise is smooth, so you can calculate it on a canvas a quarter as wide and a quarter as high. Then draw that small canvas four times bigger with drawImage(). You'll hardly see the difference, and it's a sixteenth of the work. Make the small canvas like this:

let small = document.createElement('canvas');
small.width = Math.ceil(canvas.width / 4);
small.height = Math.ceil(canvas.height / 4);

Draw the clouds pixel by pixel on small, with x * 4 and y * 4 in getCloud(), so the clouds keep their size. Then draw small over the whole canvas with context.drawImage(small, 0, 0, canvas.width, canvas.height). The browser smooths the pixels as it makes the picture bigger. Here are all three textures:

Texture

For fire and smoke, use Math.abs(value) for each octave in fractalNoise(), instead of value itself. That's called turbulence. The result is never below 0, and it has sharp creases where the noise crosses 0.

Draw a flow field

A flow field gives every spot on the canvas a direction. Particles follow those directions and leave trails behind. With Perlin noise, spots that are close together get almost the same direction, so the trails flow side by side, like water. That's how the demo at the top of this page works.

Turn the noise at each particle's position into an angle, and move the particle a little in that direction:

let particles = [];

for (let i = 0; i < 1500; i++) {
    particles.push({
        x: Math.random() * canvas.width,
        y: Math.random() * canvas.height
    });
}

function updateParticles(secondsPassed) {
    context.beginPath();
    for (let particle of particles) {
        let value = perlin2D(particle.x * 0.005, particle.y * 0.005);
        let angle = value * Math.PI * 4;
        context.moveTo(particle.x, particle.y);
        particle.x += Math.cos(angle) * 50 * secondsPassed;
        particle.y += Math.sin(angle) * 50 * secondsPassed;
        context.lineTo(particle.x, particle.y);
        let outside =
            particle.x < 0 || particle.x > canvas.width ||
            particle.y < 0 || particle.y > canvas.height;
        if (outside) {
            particle.x = Math.random() * canvas.width;
            particle.y = Math.random() * canvas.height;
        }
    }
    context.stroke();
}

Math.PI * 2 is a full circle, and an angle of 0 points to the right. The noise stays close to 0 most of the time, so if you multiply it by Math.PI * 2, most particles head roughly to the right. Multiply it by Math.PI * 4 instead, and the angles spread out over the whole circle, so the trails curl in every direction. Each frame, every particle adds a short line to its trail, and a particle that leaves the canvas starts over at a random spot.

Set context.lineWidth = 1 and context.globalAlpha = 0.08 once, before the first frame, so the lines are thin and almost transparent. Don't clear the canvas between frames, so the trails slowly build up into a picture.

Switch from Arrows to Particles to Trails to see the flow field build up step by step. Like the result? Click Save image to download it as a PNG file:

Show

In the colored version at the top of this page, each particle gets its color from another part of the noise, far from the part that sets its direction, like perlin2D(x * 0.003 + 100, y * 0.003). The range of that noise is split into six parts, one for each color, so the colors come in patches too. The lines are a little thicker, and they're drawn on a dark background.

Common questions about Perlin noise

What's the difference between Perlin noise and simplex noise?

Simplex noise is a newer kind of noise that Ken Perlin came up with in 2001. It uses triangles instead of squares, so in 2D, each point only needs three corners instead of four. That makes it faster, especially in 3D and higher dimensions, and the grid is harder to spot in the result.

Its patent expired in January 2022. OpenSimplex noise is a free alternative from 2014, made while the patent was still in force. For JavaScript, the simplex-noise library is a popular choice.

Is the noise() function in p5.js Perlin noise?

Not quite. It's often called Perlin noise, but noise() in p5.js and Processing is value noise: random values on a grid, blended with a cosine curve, with 4 octaves by default. It looks smooth, but its hills follow the grid, like the value noise at the start of this page.

Does JavaScript have a built-in noise function?

No. For randomness, Math only has Math.random(), and the canvas API has no noise function either. SVG does have a filter called <feTurbulence> that uses Perlin noise. You can use that filter as a texture on a web page, but you can't call it like a function in your own code.

Why is my Perlin noise always 0 at whole numbers?

That's how Perlin noise works. At a corner of the grid, the offset from the corner to the point is 0, so the dot product is 0 too. If you call perlin2D() with pixel positions like 10 and 20, you only hit corners, and you get 0 everywhere. Multiply the positions by a frequency like 0.01 first.

Why does my Perlin noise never get close to -1 or 1?

In 2D, Perlin noise with arrows of length 1 stays between about -0.71 and 0.71, and most values are close to 0. When we tested it, only about 6% of the values were farther from 0 than 0.4. With octaves, the values cluster even closer to 0. If you need the whole range from -1 to 1, stretch the noise yourself. For one layer of 2D noise, divide it by 0.7, and keep the result between -1 and 1 with Math.min() and Math.max().

Why does my noise look blocky or streaky?

Usually, it's because you're blending with t instead of fade(t), so you see the edges of the squares. Or you've built value noise instead of Perlin noise, so the hills sit on the grid. And with a very high frequency, every pixel lands in a different square, and the noise looks like static.

How do I get the same noise every time?

Shuffle the permutation table with a random number generator that takes a seed, like mulberry32(), as shown earlier on this page. The same seed gives the same table, and so the same noise. The tutorial about random numbers in JavaScript explains seeds.

How do I make noise that tiles seamlessly?

Make the arrows at the right edge the same as the ones at the left edge, and the ones at the bottom the same as the ones at the top. For a square texture of 8 by 8 squares, take these steps:

  • Wrap the corners - In getGradient(), use ix % 8 instead of ix, and iy % 8 instead of iy.
  • Match the size - Use a frequency of 8 / canvas.width, so the texture is exactly 8 squares wide.
  • Wrap each octave - If you use octaves, wrap each one at its own size: 8, 16, 32 and so on.

The noise then repeats every 8 squares, and the texture tiles without a seam. This only works when ix and iy are never negative, so start the texture at x = 0 and y = 0.

How do I animate noise over time, or make 3D noise?

In 3D noise, each point lies in a cube instead of a square, so you blend the dot products of 8 corners instead of 4. Use time as the third dimension, and a 2D picture changes smoothly over time. You can also move through 2D noise over time, like the clouds and the blob on this page.

What's the difference between Perlin noise and Worley noise?

Worley noise uses random points instead of a grid of arrows: its value is the distance to the closest point. That gives you cells, like stones, scales or the skin of a giraffe. It's built on a Voronoi diagram, and the tutorial about Voronoi diagrams shows how to make Worley noise.

Example code: Perlin noise

Here's an example page that puts the basics from this tutorial together in a single HTML file. It draws an island with fractal noise. The New map button makes a new island with a new seed, and Mulberry32 by Tommy Ettinger turns that seed into random numbers. Copy all of the code below into a new .html file and open that file in your browser:

Conclusion

Perlin noise gives you random values that change smoothly. It starts with a random slope at every whole number, and blends the lines through them with a fade curve. In 2D, a grid of arrows and the dot product do the same job. Add octaves for detail, and you can make hills, islands, clouds, marble, wood and flow fields, or make things move as if they're alive.

That's all for now. If you have any questions, feel free to ask them in the comment section. Made something cool with Perlin noise? Tell us about it in the comments. You can