Reputation: 782
I have two functions to display image data from a canvas, which contains some image .
This works
var canvasElement = document.getElementById("Canvas"),
canvas = canvasElement.getContext("2d");
canvas.fillStyle = "#ff6633"
canvas.fillRect(0,0,200,200);
for(x=0;x<200;x=x+10){
for(y=0;y<200;y=y+10){
p = canvas.getImageData(x, y, 1, 1).data;
console.log(p[0] + " " + p[1] + ' '+p[2]+' ' +p[3]);
}
}
but this doesn't
var canvasElement2 = document.getElementById("Canvas2"),
canvas2 = canvasElement.getContext("2d");
var image = new Image();
image.src = "b.png";
$(image).load(function() {
canvas2.drawImage(image, 0, 0,200,200);
});
canvas2.drawImage(image, 0, 0,200,200);
for(x=0;x<200;x=x+10){
for(y=0;y<200;y=y+10){
var p = canvas2.getImageData(x, y, 1, 1).data;
document.write(p[0] + " " + p[1] + ' '+' '+p[2]+' ' +p[3] +';\n');
}
}
The first method works fine, but in the second method, though the image in displayed on the canvas, all the function returns is stream of 0 0 0 0 s
What might be the mistake ?
Upvotes: 0
Views: 133
Reputation:
The reason is that you are not waiting for the image to finish loading (loading images is asynchronous) so you are iterating the image data before the load callback is invoked so the image is never drawn to the canvas before this.
If you move the iteration inside the load handler it should work:
$(image).load(function() {
canvas2.drawImage(image, 0, 0,200,200);
for(var x=0;x<200;x=x+10){
for(var y=0;y<200;y=y+10){
var p = canvas2.getImageData(x, y 1, 1).data;
document.write(p[0] + " " + p[1] + ' '+' '+p[2]+' ' +p[3] +';\n');
}
}
});
Upvotes: 1
Reputation: 572
The following works fine for me:
var canvasElement = document.getElementById("text"),
canvas = canvasElement.getContext("2d"),
x, y, p;
canvas.fillStyle = "#ff6633"
canvas.fillRect(0,0,200,200);
for(x=0;x<200;x=x+10){
for(y=0;y<200;y=y+10){
p = canvas.getImageData(x, y, 1, 1).data;
console.log(p[0] + " " + p[1] + ' '+p[2]+' ' +p[3]);
}
}
Maybe you forgot to draw anything on the canvas, or into the region of the canvas you are checking?
Upvotes: 1