问题描述
我正在尝试使用单纯形噪声创建一个 256x256 的高度图。噪声函数返回一个介于 -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,${noise})`;
ctx.fillRect(x,y,1,1)
}
}
这不起作用,我不知道如何将噪声值转换为有效颜色以绘制到画布上。任何帮助将不胜感激
解决方法
您正在尝试设置黑色的不透明度,您应该做的是通过将噪声值视为百分比来将 RG 和 B 分量设置为 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},1)`;
ctx.fillRect(x,y,1,1)
}
}