javascripthtmlcanvashtml5-canvasputimagedata

Why is Javascript Canvas putImageData drawing a white image to screen?


I am trying to draw a gray gradient (or a few of them actually) to the canvas. To do this I am using the getImageData() and putImageData() methods of canvas. data is an Uint8ClampedArray with size 1000 * 1000 * 4. In the for loops the rgb color elements of data are correctly set to be x%255, as shown by printing the data array to console. However the result of code differs from what is expected. A completely white cnvas is shown while 4 gray gradients are expected.
Minimal working example:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <canvas id = "canvas" width = "1000" height = "1000"></canvas>
        <script>
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');

            draw();

            function draw(){
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                const data = imageData.data;

                for(let y = 0; y < canvas.height; y++){
                    for(let x = 0; x < canvas.width; x++){

                        for(let color = 0; color < 3; color++){
                            let idx = (y * canvas.width + x) * 4;
                            data[idx + color] = x % 255;
                        }
                    }
                }
                ctx.putImageData(imageData, 0, 0);         
            }
        </script>
    </body>
</html>

Solution

  • You're not setting the alpha channel.

    for (let y = 0; y < canvas.height; y++) {
      for (let x = 0; x < canvas.width; x++) {
    
        let idx = (y * canvas.width + x) * 4;
        for (let color = 0; color < 3; color++) {
          data[idx + color] = x % 255;
        }
        data[idx + 3] = 255; // alpha
      }
    }