开发者

Hit detection on non-transparent pixel

开发者 https://www.devze.com 2023-01-01 01:10 出处:网络
Given a PNG in a web context with s开发者_开发问答ome 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

Given a PNG in a web context with s开发者_开发问答ome 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.


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


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.


Canvas is the way to go for this purpose. But also remember that older internet explorer versions will not be capable of the getImageData() function. Even if you include excanvas.

I made a small jquery plugin exactly for this purpose, maybe it will help you solving your problem without to completely reinvent the wheel. http://www.cw-internetdienste.de/pixelselection/

0

精彩评论

暂无评论...
验证码 换一张
取 消