使用javascript显示灰版本上的图像老鼠了
-
10-07-2019 - |
题
我需要一种能够显示一个灰度版本的图像 mouseover
.我已经看到了这个实现使用的帆布功能的浏览器,但不希望使用这一方法,因为这将是一段时间之前画布是实现在所有的浏览器。
有没有人做这样的事情?
解决方案
如果您不使用Canvas并且不想使用特定于浏览器的功能,则需要在服务器上生成灰度图像。无论是事先还是按需提供。怎么做那已经在其他地方回答了问题
其他提示
假设,正如reko_t所评论的那样,你不能仅仅出于某种原因在服务器上创建图像的灰度版本,在IE中使用专有的filter
CSS属性,带有grayScale的BasicImage 。你不需要JS来做这件事,它可以在CSS中声明:
a {
display: block;
width: 80px;
height: 15px;
background-image: url(http://www.boogdesign.com/images/buttons/microformat_hcard.png);
}
a:hover {
filter:progid:DXImageTransform.Microsoft.BasicImage(grayScale=1);
}
在Firefox中,您可以应用SVG蒙版,或者您可以尝试使用画布元件。
但是,最简单的解决方案可能是手动创建图像的灰度版本,或者使用 GD 。
找到上网:
HTML5介绍了画布的对象 可用于绘制和操纵 图像
脚本:
function grayscale(image, bPlaceImage)
{
var myCanvas=document.createElement("canvas");
var myCanvasContext=myCanvas.getContext("2d");
var imgWidth=image.width;
var imgHeight=image.height;
// You'll get some string error if you fail to specify the dimensions
myCanvas.width= imgWidth;
myCanvas.height=imgHeight;
// alert(imgWidth);
myCanvasContext.drawImage(image,0,0);
// This function cannot be called if the image is not rom the same domain.
// You'll get security error if you do.
var imageData=myCanvasContext.getImageData(0,0, imgWidth, imgHeight);
// This loop gets every pixels on the image and
for (j=0; j<imageData.height; i++)
{
for (i=0; i<imageData.width; j++)
{
var index=(i*4)*imageData.width+(j*4);
var red=imageData.data[index];
var green=imageData.data[index+1];
var blue=imageData.data[index+2];
var alpha=imageData.data[index+3];
var average=(red+green+blue)/3;
imageData.data[index]=average;
imageData.data[index+1]=average;
imageData.data[index+2]=average;
imageData.data[index+3]=alpha;
}
}
if (bPlaceImage)
{
var myDiv=document.createElement("div");
myDiv.appendChild(myCanvas);
image.parentNode.appendChild(myCanvas);
}
return myCanvas.toDataURL();
}
的使用情况:
<img id="myImage" src="image.gif"
onload="javascript:grayscale(this, true);"></img>
测试通过使用:
- FireFox3.5.4
- 铬3.0
- Safari4.0
测试失败的使用:
- Internet Explorer6
- Internet Explorer7
资源:http://www.permadi.com/tutorial/jsCanvasGrayscale/index.html
不隶属于 StackOverflow