How can I use JavaScript or jQuery to read a pixel of an image when user clicks it?

Viewed 38427

How can I use JavaScript or jQuery to read the color of a pixel of an image when the user clicks on it? (of course we have the (x,y) value of this pixel by subscribing to the click event).

2 Answers

If you can draw the image in a canvas element then you can use the getImageData method to return an array containing RGBA values.

var img = new Image();
img.src = 'image.jpg';
var context = document.getElementById('canvas').getContext('2d');
context.drawImage(img, 0, 0);
data = context.getImageData(x, y, 1, 1).data;
Related