2

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

1 Answer 1

1

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)
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this works! Although you made a little typo at fillstyle it should be color not noise.
@Ropro yea, I was in a hurry, thanks for pointing that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.