views:

1478

answers:

2

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

Thanks!

A: 

You can't read the color of an image's pixels in Javascript, since you can't read images in Javascript. You can only detect which pixel is being selected, and send this information off to something that is able to interpret the image.

An example would be getting coordinates with javascript, and using AJAX to go to a php script that finds the color at pixel (x,y) on the image. Some better methods would use flash or director since they wouldn't have to make the http request.

Ian Elliott
You meant we have to post it back to web server and handle it there?
Yes, or handle it on page with an imbedded flash/java element. But it can't be done with just javascript.
Ian Elliott
research the CANVAS/SVG/VML technologies. You can probably use them to do what you wanted. Won't be easy though if you want it to work on all browsers.
Itay Moav
+4  A: 

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;
Richard M
Also see http://stackoverflow.com/questions/667045/getpixel-from-html-canvas
Crescent Fresh