Based on Jeff's answer, the first step is to create a canvas of your PNG. The following creates an off-screen canvas that has the same width and height as your image and has the image drawn on it.
var img = document.getElementById('my-image'); var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
After that, when the user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to get the pixel:
var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;
Since you only capture one pixel, pixelData is a four-digit array containing the pixel values ββof R, G, B, and A. For alpha, anything less than 255 represents some level of transparency, with 0 being completely transparent.
Here is a jsFiddle example: http://jsfiddle.net/thirtydot/9SEMf/869/ I used jQuery for convenience in all of this, but this is by no means required.
Note. getImageData refers to a policy of the same origin of the browser to prevent data leakage, which means that this method will not succeed if you dirty the canvas with the image from another domain or (I suppose, but some browsers may have resolved this) SVG from any domain. This protects against cases where the site serves a custom image object for a registered user, and the attacker wants to read the image for information. You can solve this problem either by displaying an image from the same server or by implementing resource sharing for different sources .
Brian Nickel Jan 05 2018-12-12T00: 00Z
source share