I need to sample the pixel-color from an image, but it seems like I can’t get it right. I load the image and draw it to an off-screen canvas, then I try to sample the pixel-color but I always get 0-values.
My code:
// Create canvas and set context
var canvas = document.createElement('canvas');
canvas.width = 8;
canvas.width = 8;
var context = canvas.getContext('2d');
// Setup image
var image = new Image();
image.src = 'img.png';
image.onload = function(){
context.drawImage(image, 0, 0);
}
// Sample a random pixel from the canvas
var x = Math.floor(Math.random()*8);
var y = Math.floor(Math.random()*8);
var pixelInfo = context.getImageData(x,y,1,1);
var rgbaVal = pixelInfo.data;
alert('Image: '+image.src+'\n\nR: '+rgbaVal[0]+'\nG: '+rgbaVal[1]+'\nB: '+rgbaVal[2]+'\nA: '+rgbaVal[3]+'\n\nCoords: '+x+', '+y);
I get no errors and if I try to draw the image on an on-screen canvas, the image draws correctly. I can’t manage to find the problem
Because the image hasnt been loaded and drawn yet. You draw it after the onload is fired, then you should get the RGB value too.
The image.onload function will fire later then your sampling function, so you just sample an empty canvas at the moment.