javascriptcanvasputimagedataimagedata

JavaScript: canvas PutImageData not working?


I was working with imageData, and for some reason, it is only drawing half of the image!

Here is my code. (There is a canvas element with an ID of canvas)

function getWidth() {
  return Math.max(
    document.body.scrollWidth,
    document.documentElement.scrollWidth,
    document.body.offsetWidth,
    document.documentElement.offsetWidth,
    document.documentElement.clientWidth
  );
}
function getHeight() {
  return Math.max(
    document.body.scrollHeight,
    document.documentElement.scrollHeight,
    document.body.offsetHeight,
    document.documentElement.offsetHeight,
    document.documentElement.clientHeight
  );
}

var width = getWidth();
var height = getHeight();

var canvas = document.getElementById('canvas');
canvas.setAttribute("width", width + "px");
canvas.setAttribute("height", height + "px");

var ctx = canvas.getContext('2d');

var draw = function(){
    var p = new Uint8ClampedArray(width*height*4);

    for(var y = 0; y<width; y++){
        for(var x = 0; x<height; x++){
            var i = x + width * y << 2;
            p[i    ] = p[i + 1] = p[i + 2] = 0;
            p[i + 3] = 255;
        }
    }

    var imageData = new ImageData(p, width, height);      
    ctx.putImageData(imageData, 0, 0);

    window.requestAnimationFrame(draw);
};

window.requestAnimationFrame(draw);
<canvas id="canvas"></canvas>


Solution

  • I mixed up width and height in the for loops! I was writing to the array sideways.

    Once the width and height are swapped, everything works fine :)

    function getWidth() {
      return Math.max(
        document.body.scrollWidth,
        document.documentElement.scrollWidth,
        document.body.offsetWidth,
        document.documentElement.offsetWidth,
        document.documentElement.clientWidth
      );
    }
    function getHeight() {
      return Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight,
        document.body.offsetHeight,
        document.documentElement.offsetHeight,
        document.documentElement.clientHeight
      );
    }
    
    var width = getWidth();
    var height = getHeight();
    
    var canvas = document.getElementById('canvas');
    canvas.setAttribute("width", width + "px");
    canvas.setAttribute("height", height + "px");
    
    var ctx = canvas.getContext('2d');
    
    var draw = function(){
        var p = new Uint8ClampedArray(width*height*4);
    
        for(var y = 0; y<height; y++){
            for(var x = 0; x<width; x++){
                var i = x + width * y << 2;
                p[i    ] = p[i + 1] = p[i + 2] = 0;
                p[i + 3] = 255;
            }
        }
    
        var imageData = new ImageData(p, width, height);      
        ctx.putImageData(imageData, 0, 0);
    
        window.requestAnimationFrame(draw);
    };
    
    window.requestAnimationFrame(draw);
    <canvas id="canvas"></canvas>