简体   繁体   中英

Can't get pixel color from canvas

I'm having trouble getting color information from pixels on a canvas.

var canvas = document.getElementById('frame');
var context = canvas.getContext('2d');
var img = new Image();
var source = $("#image").attr("src");

img.src = source;
$(img).load(function() {
   context.drawImage(img, 0, 0);
});

var imgd = context.getImageData(0, 0, 50, 50);
var pix = imgd.data;

for (var i = 0, n = pix.length; i < n; i += 4) {
  console.log(pix[i] +", "+ pix[i+1] +", "+ pix[i+2] +", "+ pix[i+3]);
}

(So I'm getting the src from another image on the page and drawing it on the canvas. Which is working fine, I can see the image on the canvas.)

To my understanding, each time the for loop runs, this code should log the red, green, blue, and alpha values to the console for the first 50X50 pixels.

Instead, all I get are zeros.

零

etc...

Thanks in advance for the help!

Try this way:

$(img).load(function() {
    context.drawImage(img, 0, 0);

    var imgd = context.getImageData(0, 0, 50, 50);
    var pix = imgd.data;

    for (var i = 0, n = pix.length; i < n; i += 4) {
      console.log(pix[i] +", "+ pix[i+1] +", "+ pix[i+2] +", "+ pix[i+3]);
    }
});

At the time your image has loaded the loop is probably done with the buffer iterating so the buffer will be empty due to the image loading is asynchronously.

Besides from that there is the possibility of CORS restrictions (you need to check in console to see if there's any security errors).

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