I can’t seem to get pixel data from my canvas (Chrome 12). What am I doing wrong?
Complete example. All my console logs come at as zero. I would expect a mixture of black and white pixels.
Clarification: I’m drawing a black square to test that I can retrieve the pixel data correctly. I would expect some 255, 255, 255 (white) and some 0, 0, 0 (black). I only get white pixel data.
<html>
<canvas id="canvas" style="border: 1px solid black" width="20" height="20"></canvas>
<script>
var x;
var y;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// some of the pixels should be black, some white.
context.fillRect(0, 0, 10, 10);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
for (y = 0; y < imageData.height; y ++)
{
for (x = imageData.width - 1; x >= 0; x--)
{
console.log(x, y,
imageData.data[((y*(imageData.width*4)) + (x*4)) + 0],
imageData.data[((y*(imageData.width*4)) + (x*4)) + 1],
imageData.data[((y*(imageData.width*4)) + (x*4)) + 2]);
}
}
</script>
</html>
I tried, and experienced the same thing. Why? Look at the alpha channel: the areas you see as white on the picture, are in fact black with an opacity value of 0 (this means they are fully transparent). Thus, you see through, aka. the background, which is white.
If you first draw a white 20×20 rectangle, then a black 10×10 rectangle, everything will be working fine (have a look here).