# Simplex Noise Generator In JavaScript

Category: Javascript , Recommended | August 31, 2021
Author: jwagner 360 views Go to website August 31, 2021 MIT

## Description:

A deterministic simplex noise generator suitable for 2D, 3D, and 4D spaces.

Works in both browser and node.js.

## How to use it:

1. Install and import the simplex-noise.js library.

```# NPM
\$ npm i simplex-noise --save```
```// ES Module
import SimplexNoise from 'simplex-noise';
// commonjs
const {SimplexNoise} = require('simplex-noise');
// from CDN
import SimplexNoise from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/esm/simplex-noise.js';```

2. Create a canvas element on which you want to generate the simplex noise effect.

`<canvas id="example"></canvas>`

3. This example shows how to generate a basic noise effect in 2D space.

```var simplex = new SimplexNoise(),
canvas = document.getElementById('example'),
ctx = canvas.getContext('2d'),
imgdata = ctx.getImageData(0, 0, canvas.width, canvas.height),
data = imgdata.data,
t = 0;
window.setInterval(function () {
for (var x = 0; x < 256; x++) {
for (var y = 0; y < 256; y++) {
var r = simplex.noise3D(x / 16, y / 16, t / 16) * 0.5 + 0.5;
var g = simplex.noise3D(x / 8, y / 8, t / 16) * 0.5 + 0.5;
data[(x + y * 256) * 4 + 0] = r * 255;
data[(x + y * 256) * 4 + 1] = (r + g) * 200;
data[(x + y * 256) * 4 + 2] = 0;
data[(x + y * 256) * 4 + 3] = 255;
}
}
t++;
ctx.putImageData(imgdata, 0, 0);
}, 1000 / 60);```

4. Generate the noise field in 2 dimensions. Returns a number in the interval [-1, 1]

`noise2D(x: number, y: number);`

5. Generate the noise field in 3 dimensions. Returns a number in the interval [-1, 1]

`noise3D(x: number, y: number, z: number)`

6. Generate the noise field in 4 dimensions. Returns a number in the interval [-1, 1]

`noise4D(x: number, y: number, z: number, w: number)`

7. Seed the noise functions.

```const simplex = new SimplexNoise('seed'),
value2d = simplex.noise2D(x, y),
sameSeed = new SimplexNoise('seed'),
differentSeed = new SimplexNoise('different seed');
sameSeed.noise2D(x, y) === value2d
differentSeed.noise2D(x, y) !== value2d```