user1601513
user1601513

Reputation: 153

javascript getImageData not returning correct pixel color from png image

I am trying to use getImageData to return the x-position of the first non-white pixel from the left edge of a png image like this;

    function getLeftEdge(myImage) {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var img = document.getElementById(myImage);
        context.drawImage(img, 0, 0);
        var pixelData;

        for (x = 1; x <= img.width; x++) {
            for (y = 1; y <= img.height; y++) {
                pixelData = context.getImageData(x, y, 1, 1);
                if (pixelData.data[0] != 255) {
                    alert("return x,y " + x + "," + y);
                    return x;
                }
            }
        }
    }

I know that the first non-white pixel in the image that I am using is at 222,254 but the function that I made is reporting 1,150 instead. I tried to make a jsfiddle, it doesn't work but you can see the image that I am using.

Upvotes: 1

Views: 1510

Answers (1)

just95
just95

Reputation: 1099

The problem is that you do not set the size of the canvas. It therefore defaults to 150x300 pixels. You also start iterating at 1,1 and stop at width,height but the top left pixel is actually 0,0 and bottom right pixel is width-1,height-1. When the loop reaches 1,150 there is no pixel at this position because the maximum is 149 for the y coordinate. This is why getImageData reports that the pixel is black.

function getLeftEdge(myImage) {
    var img = document.getElementById(myImage);
    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    var context = canvas.getContext('2d');
    context.drawImage(img, 0, 0);
    var pixelData;

    for (var x = 0; x < img.width; x++) {
        for (var y = 0; y < img.height; y++) {
            pixelData = context.getImageData(x, y, 1, 1);
            if (pixelData.data[0] != 255) {
                alert("return x,y " + x + "," + y);
                return x;
            }
        }
    }
}

This, however, does not fix the problem, because although it appears as if the background is completely white there some pixels which are for example #fefefe. You should consider to use a higher threshold.

Upvotes: 3

Related Questions