Search code examples
javascriptthree.jsnoisesimplex-noise

Transforming simplex noise value to color


I am trying to create a 256x256 heightmap using simplex noise. The noise function returns a value between -1 and 1 and this is my current attempt to turn that value into a gray value.

    import { SimplexNoise } from "three/examples/jsm/math/SimplexNoise";

    const ctx = document.createElement("canvas").getContext("2d");
    ctx.canvas.width = 256;
    ctx.canvas.height = 256;

    const simplex = new SimplexNoise();
    for(let y = 0; y < ctx.canvas.width; y++) {
        for(let x = 0; x < ctx.canvas.width; x++) {
            let noise = simplex.noise(x, y);
            noise = (noise + 1) / 2;
            ctx.fillStyle = `rgba(0, 0, 0, ${noise})`;
            ctx.fillRect(x, y, 1, 1)
        }
    }

This does not work and I do not know how to turn the noise value into a valid color to draw onto the canvas. Any help would be apreciated


Solution

  • You are trying to set opacity of a black color, what you should do is to convert noise to grayscale by setting R G and B components to value from 0 to 255 by treating noise value as percentage, for example by getting it's absolute value and multiplying it by 255 while setting it's opacity to 1:

    import { SimplexNoise } from "three/examples/jsm/math/SimplexNoise";
    
    const ctx = document.createElement("canvas").getContext("2d");
    ctx.canvas.width = 256;
    ctx.canvas.height = 256;
    
    const simplex = new SimplexNoise();
    for(let y = 0; y < ctx.canvas.width; y++) {
        for(let x = 0; x < ctx.canvas.width; x++) {
            let noise = simplex.noise(x, y);
            noise = (noise + 1) / 2;
            let color = Math.abs(noise) * 255;
            ctx.fillStyle = `rgba(${color}, ${color}, ${color}, 1)`;          
            ctx.fillRect(x, y, 1, 1)
        }
    }