Canvas.putImageDate - Weird Behaviour

39 Views Asked by At

I'm trying to use perlin noise to create a noise map using html canvas.

Here's my code:

            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)

Contextual Information:

noiseMap is a bidimensional array that contains numbers from 0 to 1 (floatish). The noise map array sizes are equal to the canvas width / height.

Once I run this code, the canvas doesn't get painted at all. Curiously, if I remove index multiplication from:

const pixelIndex = index * 4

to

const pixelIndex = index

It renders this:

enter image description here Note that noise map get clamped, because I'm not properly assigning data to imageData.data. In fact, about 3/4 of the imageData.data array receives 0.

So I definitely need to multiply the pixelIndex by 4. Which based on console log properly populate my imageData.data array.

So I'm wondering what may be happening.... any clues?

1

There are 1 best solutions below

0
Thiago Facchini On

Thanks everyone who tried to help.

The issue was quite simple, the line:

pixelIndex = index * 4

was the cause, it would blow the imagedata.data array by one position, so the solution was quite simple:

pixelIndex = (index * 4) -1

Done.