2010-05-20 74 views
11

給定一個帶有一些透明像素和一些不透明像素的web上下文中的PNG,Javascript中有一種方法可以確定用戶是否點擊了非透明像素?僅webkit解決方案將是完全可以接受的。不透明像素點擊檢測

回答

24

1)創建相同大小的HTML5畫布作爲圖像
2)獲取畫布的上下文,的drawImage(yourImage,0,0)
3)d = context.getImageData(0,0,W IMG的,H IMG
4)d.data [(Y *寬度+ X)* 4 + 3]爲阿爾法

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 
+0

好的。那很好!當我得到更多選票時,在34分鐘內爲您+1 !-) – Josh 2010-05-20 23:25:11

8

的)我知道這些東西都是出的時尚這些天,但HTML image maps仍然有效,並且可以實現將圖像中的幾乎任意形狀的擊中目標加入。如果您實際上並不想在點擊時重新載入另一個頁面,則可以使用此技術更改URL中的錨點,然後以Javascript時間間隔獲取更改。

0

畫布是爲此目的而走的路。但是請記住,較舊的Internet Explorer版本將無法使用getImageData()功能。即使你包含excanvas。

我爲此目的製作了一個小的jquery插件,也許它可以幫助您解決問題,而不會完全重新發明輪子。 http://www.cw-internetdienste.de/pixelselection/