javascripthtml5-canvasimagedata

Can't get the pixels from ImageData object


I'm trying to extract pixels from an image using a canvas element and the ImageData class, but with little to no success.

My code is:

var image = new Image();
image.src = "<path to PNG image file>";
var context = document.getElementById("my-canvas").getContext("2d");
context.drawImage(image, 0, 0);
var imageData = context.getImageData(0, 0, 1024, 1024);
console.log(imageData);

And the canvas is defined like this:

<canvas id ="my-canvas" width="1024" height="1024">
</canvas>

According to MDN the data field should be a 4194304 (1024*1024*4) size array of UInt8. Instead, I get a weirdly nested structure (as the picture shows), and all values are 0. The image is a 1024*1024 PNG image.

Where am I doing wrong?

enter image description here


Solution

  • You should wait until your PNG is loaded (ImageData is initialized with zeros):

    var image = new Image();
    image.onload = extractPixelsFromPNG;
    image.src = "<path to PNG image file>";
    var context = document.getElementById("my-canvas").getContext("2d");
    
    function extractPixelsFromPNG() {
        context.drawImage(image, 0, 0);
        var imageData = context.getImageData(0, 0, 1024, 1024);
        console.log(imageData);
    }