Reputation: 47729
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>
Upvotes: 1
Views: 2630
Reputation: 6762
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 20x20 rectangle, then a black 10x10 rectangle, everything will be working fine (have a look here).
Upvotes: 3
Reputation: 154948
You're iterating from 0
to height - 2
, whilst your calculations say something else. Your calculations use the full height and width.
Secondly, white pixels are not white but transparent. Because if you change body background to green, the pixels become green. The alpha property confirms this (index 3 of data): http://jsfiddle.net/va3C5/1/.
Your white pixels are shining through the body background color (which is white) - the pixels of the canvas are not white but transparent.
So to come to the point, just iterate like:
for(var x = 0; x < imageData.width; i++) { ... }
and the same for y respectively. And keep in mind about the transparency.
Upvotes: 1