user2108742
user2108742

Reputation: 117

Why my canvas getImageData doesn't work?

I am trying to pick up a color from a image pixel with that simple code :

<body>
    <img src="image.png" id="monImage"/>
    <canvas id="myCanvas"></canvas>
    <script src="jquery.js"></script>
    <script>
        $(function() {
            var img = $('#monImage')[0];
            var canvas = $('#myCanvas')[0];
            canvas.width = img.width;
            canvas.height = img.height;
            canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

            var pixelData = canvas.getContext('2d').getImageData(0, 0, 1, 1);

            alert("test");
        });
    </script>
</body>

I am using jquery so it's easier to select element. If I comment this line :

var pixelData = canvas.getContext('2d').getImageData(1, 1, 1, 1);

Then the alert() works and apears on my screen. But if I don't comment it doesn't, so that line doesn't works. Why ?

Thanks

Upvotes: 0

Views: 2051

Answers (1)

user1693593
user1693593

Reputation:

At the point your function executes the image is not done loading (image data is not available).

The image element is valid however so you can read its properties. This is why it doesn't fail before, but its width and height properties will be 0.

A little bitsurprising is that you can execute the line with drawImage. However at the point you get to getImageData there is no data to retrieve and therefor it will fail.

You need to either put your code inside a window load event handler or add an event listener to the image element.

For example:

window.onload = function() {

    /// your function goes here

}

Upvotes: 2

Related Questions