简体   繁体   中英

Getting image data from canvas

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 ?

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?

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');
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM