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

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

+35
javascript jquery
Jun 24 '09 at 22:51
source share
2 answers

If you can draw an image in a canvas element, 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; 
+39
Jun 24 '09 at 23:29
source share

I was looking for a way to count the green pixels in an image, eventually wrote my own functions. Here you go

Magic ยฎ

 function getPixel(imgData, index) { var i = index*4, d = imgData.data; return [d[i],d[i+1],d[i+2],d[i+3]] // [R,G,B,A] } function getPixelXY(imgData, x, y) { return getPixel(imgData, y*imgData.width+x); } 

Where do you get imgData?

  • create <canvas>
  • get canvas context
  • copy <img> to <canvas>
  • get canvas image data (array of values [r,g,b,a,r,g,b,a,r,g,..] )
  • make `The magic`ยฎ

the code:

 var cvs = document.createElement('canvas'), img = document.getElementsByTagName("img")[0]; // your image goes here // img = $('#yourImage')[0]; // can use jquery for selection cvs.width = img.width; cvs.height = img.height; var ctx = cvs.getContext("2d"); ctx.drawImage(img,0,0,cvs.width,cvs.height); var idt = ctx.getImageData(0,0,cvs.width,cvs.height); // The magicยฎ getPixel(idt, 852); // returns array [red, green, blue, alpha] getPixelXY(idt,1,1); // same pixel using x,y 

For a working example, see the source code http://qry.me/xyscope/

+6
Dec 30 '15 at 12:40
source share



All Articles