JavaScript eyedropper (tell color of pixel under mouse cursor)

It’s not possible with JavaScript as it goes against cross-domain security. It would be very bad if you knew what pixels made up the image, http://some-other-host/yourPassword.png. You can only tell the color of the pixel under the mouse if either the mouse is over a canvas or an image element of the same domain (or an image element of another domain which is served with an Access-Control-Allow-Origin: * header). In the case of the canvas, you would do canvasElement.getContext('2d').getImageData(x, y, 1, 1).data. In the case of the images, you would have to draw them to a canvas with:

var canvas = document.createElement("canvas");
canvas.width = yourImageElement.width;
canvas.height = yourImageElement.height;
canvas.getContext('2d').drawImage(yourImageElement, 0, 0);

And then just use the previous method explained for canvases. If you must be able to convert to various representations of color values, try my color.js library.

Also, you’re never going to be able to support IE <9 (that’s assuming that IE9 supports canvas) and using Flash won’t help as it can’t read the pixel data of the document either.

Leave a Comment