So, I have a function like this:
var getRGBArray = function (img) {
// create the canvas we need to work with
var canvas = document.createElement('canvas');
// get the canvas context
var context = canvas.getContext("2d");
// will store the image data and the returned array
var imgData, rgbArray = [];
// make sure that the width and height are correct
context.canvas.width = img.naturalWidth;
context.canvas.height = img.naturalHeight;
// draw the image
context.drawImage(img, img.naturalWidth, img.naturalHeight);
// get the image data
imgData = context.getImageData(0, 0, img.naturalWidth, img.naturalHeight);
// imgData contains r,g,b,alpha values. We skip
// the alpha value.
for (var i = 0, n = 0; i < imgData.data.length; i+=4, n+=3) {
rgbArray[n] = imgData.data[i];
rgbArray[n+1] = imgData.data[i+1];
rgbArray[n+2] = imgData.data[i+2];
// imgData.data[i+3] is the alpha channel. We ignore it.
}
return rgbArray;
};
Which is just supposed to take an image and return an array that's set up like [r0, g0, b0, r1, g1, b1, ..., rn, gn, bn]
.
First, the array that is returned is completely empty, which is obviously a problem.
Second, when I input all of this stuff into the console window on Firefox, the imgData
array is a reasonable length, but all of the data is 0! None of the values are coming up undefined, and I have a simple webpage I'm debugging on. The webpage already has the image loaded, and I'm just getting the image using document.getElementById('testImage')
.
Can someone please explain to me why this is happening?
EDIT: This is different from this because I was wondering why drawImage()
was giving me back a data array with all 0's. They are asking completely different things.