Skip to content

Instantly share code, notes, and snippets.

@maticzav
Created May 7, 2023 20:46
Show Gist options
  • Save maticzav/e3743390e112c50b692b6de5c16d8582 to your computer and use it in GitHub Desktop.
Save maticzav/e3743390e112c50b692b6de5c16d8582 to your computer and use it in GitHub Desktop.
import path from 'node:path'
import fs from 'node:fs/promises'
import { createNoise2D } from 'simplex-noise'
import { createCanvas, createImageData } from 'canvas'
const OUTPUT_PATH = path.join(__dirname, '../../web/public/noise.png')
/**
* Creates a 200x200 canvas with a noise pattern.
*/
export function makeSomeNoise() {
const noise2D = createNoise2D()
const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d')
const imageData = createImageData(200, 200)
for (let x = 0; x < 200; x++) {
for (let y = 0; y < 200; y++) {
const cell = (x + y * 200) * 4
// https://cmaher.github.io/posts/working-with-simplex-noise/
const luminance = transform(noise2D(x, y), [-1, 1], [175, 255])
imageData.data[cell] = luminance
imageData.data[cell + 1] = luminance
imageData.data[cell + 2] = luminance
imageData.data[cell + 3] = luminance
}
}
ctx.putImageData(imageData, 0, 0)
return canvas.toBuffer()
}
async function main() {
const png = makeSomeNoise()
await fs.writeFile(OUTPUT_PATH, png)
}
// Start
if (require.main === module) {
main()
.then(() => {
console.log(`Noise written to ${OUTPUT_PATH}`)
})
.catch((error) => {
console.error(error)
process.exit(1)
})
}
/**
* Transforms a value from one range to another.
*/
function transform(val: number, input: [number, number], output: [number, number]): number {
const [inputMin, inputMax] = input
const [outputMin, outputMax] = output
return ((val - inputMin) / (inputMax - inputMin)) * (outputMax - outputMin) + outputMin
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment