【发布时间】:2010-12-11 05:50:45
【问题描述】:
我需要一种方法来在mouseover 上显示图像的灰度版本。我已经看到使用浏览器的 Canvas 功能实现了这一点,但不想使用该方法,因为在所有浏览器上实现 canvas 还需要一段时间。
有人做过这样的事吗?
【问题讨论】:
-
你的意思是不先在服务器端预先生成灰度图?
标签: javascript image mouseover grayscale
我需要一种方法来在mouseover 上显示图像的灰度版本。我已经看到使用浏览器的 Canvas 功能实现了这一点,但不想使用该方法,因为在所有浏览器上实现 canvas 还需要一段时间。
有人做过这样的事吗?
【问题讨论】:
标签: javascript image mouseover grayscale
网上找的:
HTML 5 引入了 Canvas 对象 可用于绘制和操作 图片
脚本:
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>
通过的测试:
测试失败使用:
资源: http://www.permadi.com/tutorial/jsCanvasGrayscale/index.html
【讨论】:
假设,正如 reko_t 评论的那样,由于某种原因,您不能只在服务器上创建图像的灰度版本,在 IE 中使用专有的filter CSS 属性BasicImage with grayScale 是可能的。你不需要 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 中,您可以apply an SVG mask,或者您可以尝试使用画布元素。
但是,最简单的解决方案可能是手动创建图像的灰度版本,或者在服务器端使用 GD 之类的东西。
【讨论】:
如果您不使用 Canvas 并且不想使用特定于浏览器的功能,则需要在服务器上生成灰度图像。提前或按需。怎么办 一直是answered elsewhere on SO
【讨论】:
img {
mix-blend-mode: luminosity;
background: #000;
}
【讨论】:
:hover 伪类,因为问题在鼠标悬停时要求这样做。