我正在尝试使用 perlin 噪声来使用 html 画布创建噪声图。
这是我的代码:
const width = noiseMap.length
const height = noiseMap[0].length
const colorMap = new Array(width * height).fill(0)
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
const imageData = ctx.createImageData(width, height)
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const index = y * width + x
const pixelIndex = index * 4
const rgbaColor: rgbaColorType = hexRgb(lerp('#FFFFFF', '#000000', noiseMap[x][y]))
colorMap[index] = rgbaColor
imageData.data[pixelIndex] = rgbaColor.red
imageData.data[pixelIndex + 1] = rgbaColor.green
imageData.data[pixelIndex + 2] = rgbaColor.blue
imageData.data[pixelIndex + 3] = rgbaColor.alpha
}
}
console.log(imageData)
ctx.putImageData(imageData, 0, 0)
上下文信息:
NoiseMap是一个二维数组,包含从 0 到 1 的数字(浮动)。噪声图数组大小等于画布宽度/高度。
运行此代码后,画布根本不会被绘制。奇怪的是,如果我从以下位置删除索引乘法:
const pixelIndex = index * 4
至
const pixelIndex = index
它呈现:
请注意,噪声图被固定,因为我没有正确地将数据分配给 imageData.data。事实上,大约 3/4 的 imageData.data 数组接收到 0。
所以我肯定需要将 pixelIndex 乘以 4。根据控制台日志正确填充我的 imageData.data 数组。
所以我想知道可能会发生什么......任何线索?