Getimagedata() Returning All Zeros
I'm trying to output the pixel values from an image. The image is loading correctly; another answer on here suggested that the browswer is trying to read the pixels before the imag
Solution 1:
Image.onload()
is called asynchronously when the image has been loaded. That can happen after your current code calls context.getImageData()
.
The following code should work:
functioninitContext(canvasID, contextType)
{
var canvas = document.getElementById(canvasID);
var context = canvas.getContext(contextType);
return context;
}
functionloadImage(imageSource, context)
{
var imageObj = newImage();
imageObj.onload = function()
{
context.drawImage(imageObj, 0, 0);
var imageData = context.getImageData(0,0,10,10);
readImage(imageData);
};
imageObj.src = imageSource;
return imageObj;
}
functionreadImage(imageData)
{
console.log();
console.log(imageData.data[0]);
}
var context = initContext('canvas','2d');
var imageObj = loadImage('images/color-test.png',context);
If you want to access the imageData
value outside of loadImage()
, you have 2 basic choices:
- Store the
imageData
in a variable that is declared outside the function. In this case, the value will be unset until youronload()
is called, so the outside code would have to test it for reasonableness before callingreadImage(imageData)
. - Have the outside code register a callback function, and have your
onload()
call that function with theimageData
value.
Solution 2:
It is also possible you are evaluating a portion of an image that is transparent. I had this issue while scanning a PNG.
Post a Comment for "Getimagedata() Returning All Zeros"