当我悬停在PNG的透明部分上时,它仍然像我在实际图像上盘旋一样。有什么办法可以防止这种情况发生吗?所以只有当我悬停在图像的可见部分,而不是透明部分时,它才会采取行动?
我试着把透明度调出来,但我想不出怎么做。
发布于 2014-02-04 22:17:48
可以通过将png转换为画布元素来完成。
这可以通过将png加载到HTML-5画布元素中,然后在画布上查询单击像素的alpha值。
工作演示:http://jsfiddle.net/x9ScK/3/
HTML如下..。
<!-- create a canvas element to hold the PNG image -->
<canvas id="canvas1" width="500" height="500"></canvas>像这样的Javascript。
// select the canvas element with jQuery, and set up
// a click handler for the whole canvas
$('#canvas1').on('click', function(e) {
// utility function for finding the position of the clicked pixel
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
// get the position of clicked pixel
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
// get reference to canvas element clicked on
var canvas = this.getContext('2d');
// return array of [RED,GREEN,BLUE,ALPHA] as 0-255 of clicked pixel
var pixel = canvas.getImageData(x, y, 1, 1).data;
// if the alpha is not 0, we clicked a non-transparent pixel
// could be easily adjusted to detect other features of the clicked pixel
if(pixel[3] != 0){
// do something when clicking on image...
alert("Clicked the dice!");
}
});
// get reference to canvas DOM element
var canvas = $('#canvas1')[0];
// get reference to canvas context
var context = canvas.getContext('2d');
// create an empty image
var img = new Image();
// after loading...
img.onload = function() {
// draw the image onto the canvas
context.drawImage(img, 0, 0);
}
// set the image source (can be any url - I used data URI to keep demo self contained)
img.src = "data:image/png;base64,iVBORw0KGgoAAAANS ... more image data ...TkSuQmCC"; // PNG with transparency发布于 2014-02-04 22:08:03
我知道我见过一些网站可以让你根据你在上面盘旋的像素“选择一个颜色”。我不知道他们是如何做到的,但有一个选择是创建一个html图像地图(如下所示),这样您的PNG的不同部分就会触发“悬停”,而其他部分就不会触发。本质上,鼠标不是在PNG上盘旋,而是在您在HTML中定义的区域上徘徊。
下面是我直接从上面的链接中获取的一个例子:
<body>
<img src="trees.gif" usemap="#green" border="0">
<map name="green">
<area shape="polygon" coords="19,44,45,11,87,37,82,76,49,98" href="http://www.trees.com/save.html">
<area shape="rect" coords="128,132,241,179" href="http://www.trees.com/furniture.html">
<area shape="circle" coords="68,211,35" href="http://www.trees.com/plantations.html">
</map>
</body>https://stackoverflow.com/questions/21564447
复制相似问题