是否有一个简单的方法来显示一个彩色位图的灰度与只是HTML/CSS?

它不需要与ie兼容(我想它也不会)——如果它能在FF3和/或Sf3中工作,那对我来说就足够了。

我知道我可以用SVG和Canvas来做,但现在看起来工作量很大。

真的有懒人能做到的方法吗?


当前回答

作为对其他人答案的补充,可以在FF上降低图像的饱和度,而不会出现SVG矩阵的头痛问题:

<feColorMatrix type="saturate" values="$v" />

其中$v在0和1之间。相当于filter:grayscale(50%);。

生活例子:

.desaturate { filter: url("#desaturate"); -webkit-filter: grayscale(50%); } figcaption{ background: rgba(55, 55, 136, 1); padding: 4px 98px 0 18px; color: white; display: inline-block; border-top-left-radius: 8px; border-top-right-radius: 100%; font-family: "Helvetica"; } <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <filter id="desaturate"> <feColorMatrix type="saturate" values="0.4"/> </filter> </svg> <figure> <figcaption>Original</figcaption> <img src="http://www.placecage.com/c/500/200"/> </figure> <figure> <figcaption>Half grayed</figcaption> <img class="desaturate" src="http://www.placecage.com/c/500/200"/> </figure>

MDN参考资料

其他回答

今天又遇到了同样的问题。我最初使用SalmanPK解决方案,但发现FF和其他浏览器之间的效果不同。这是因为转换矩阵只对亮度有效,而不是像Chrome/IE中的滤镜那样对亮度有效。令我惊讶的是,我发现SVG中的另一种更简单的解决方案也适用于FF4+,并产生更好的结果:

<svg xmlns="http://www.w3.org/2000/svg">
  <filter id="desaturate">
    <feColorMatrix type="saturate" values="0"/>
  </filter>
</svg>

用css:

img {
    filter: url(filters.svg#desaturate); /* Firefox 3.5+ */
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(1); /* Google Chrome & Safari 6+ */
}

需要注意的是,IE10在标准兼容模式下不再支持“filter: gray:”,所以需要在头文件中切换兼容模式才能工作:

<meta http-equiv="X-UA-Compatible" content="IE=9" />

一个糟糕但可行的解决方案是:使用Flash对象渲染图像,然后在Flash中为您提供所有可能的转换。

如果您的用户使用尖端浏览器,并且Firefox 3.5和Safari 4支持它(我不知道是否支持),您可以调整图像的CSS颜色配置文件属性,将其设置为灰度ICC配置文件URL。但那有很多假设!

用CSS实现灰度最简单的方法是通过filter属性。

img {
    -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
    filter: grayscale(100%);
}

该属性仍然不完全支持,并且仍然需要-webkit-filter属性来支持所有浏览器。

作为对其他人答案的补充,可以在FF上降低图像的饱和度,而不会出现SVG矩阵的头痛问题:

<feColorMatrix type="saturate" values="$v" />

其中$v在0和1之间。相当于filter:grayscale(50%);。

生活例子:

.desaturate { filter: url("#desaturate"); -webkit-filter: grayscale(50%); } figcaption{ background: rgba(55, 55, 136, 1); padding: 4px 98px 0 18px; color: white; display: inline-block; border-top-left-radius: 8px; border-top-right-radius: 100%; font-family: "Helvetica"; } <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <filter id="desaturate"> <feColorMatrix type="saturate" values="0.4"/> </filter> </svg> <figure> <figcaption>Original</figcaption> <img src="http://www.placecage.com/c/500/200"/> </figure> <figure> <figcaption>Half grayed</figcaption> <img class="desaturate" src="http://www.placecage.com/c/500/200"/> </figure>

MDN参考资料

webkit中对本地CSS过滤器的支持已从当前版本19.0.1084.46添加

所以-webkit-filter:灰度(1)将工作,这是更容易为webkit的SVG方法…