我正试图使用单纯形噪声创建一个256x256高度图。noise函数返回一个介于-1和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;
ctx.fillStyle = `rgba(0, 0, 0, ${noise})`;
ctx.fillRect(x, y, 1, 1)
}
}
这不起作用,我不知道如何将噪波值转换为有效的颜色以绘制到画布上。任何帮助都将被视为
您正在尝试设置黑色的不透明度,您应该做的是通过将RGB分量设置为0到255的值来将噪声转换为灰度,方法是将噪声值视为百分比,例如,获取其绝对值并乘以255,同时将不透明度设置为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)
}
}