Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hit detection on non-transparent pixel

Given a PNG in a web context with some transparent pixels and some non-transparent pixels, is there a way in Javascript to determine if a user has clicked on a non-transparent pixel? A webkit-only solution would be perfectly acceptable.

like image 286
Abie Avatar asked May 20 '10 23:05

Abie


2 Answers

1) Create HTML5 canvas of same size as your image
2) Get Canvas's context, drawImage(yourImage, 0, 0)
3) d = context.getImageData(0, 0, w of img, h of img)
4) d.data[(y*width+x)*4+3] for the alpha

canvas = document.createElement("canvas");  //Create HTML5 canvas: supported in latest firefox/chrome/safari/konquerer.  Support in IE9
canvas.width = img.width;                   //Set width of your rendertarget
canvas.height = img.height;                 // \  height \   \     \
ctx = canvas.getContext("2d");              //Get the 2d context [the thing you draw on]
ctx.drawImage(img, 0, 0);                   //Draw the picture on it.
id = ctx.getImageData(0,0, img.width, img.height);  //Get the pixelData of image
//id.data[(y*width+x)*4+3] for the alpha value of pixel at x,y, 0->255
like image 153
Warty Avatar answered Oct 24 '22 05:10

Warty


I know these things are out of fashion these days, but HTML image maps are still valid, and can accomplish adding hit targets to nearly-arbitrary shapes within an image. If you don't actually want to reload another page on click, you could probably change the anchor in the URL with this technique and pick up the change with a Javascript interval.

like image 30
Ben Zotto Avatar answered Oct 24 '22 05:10

Ben Zotto