Hit detection on non-transparent pixel

天大地大妈咪最大 提交于 2019-11-29 03:51:09

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!