如何在CSS / JAVASCRIPT中将图像转换为灰度

时间:2014-09-05 13:23:54

标签: javascript jquery css svg html5-canvas

我想在Javascript / CSS

中将图像(设置为背景)转换为灰度

这里的问题是灰度的CSS3过滤器在IE中不起作用 由于图像是跨域资源,因此我无法从画布中读取数据。 我的目标浏览器是Firefox,Chrome,IE10以后的

我尝试过使用以下

filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale"); 

这在IE10和IE11中不起作用

<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 400 377" width="400" height="377">
  <defs>
     <filter id="filtersPicture">
       <feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />
       <feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />
    </filter>
  </defs>
  <image filter="url(&quot;#filtersPicture&quot;)" x="0" y="0" width="400" height="377" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="whateverpathtoimage.jpg" />
</svg> 

我无法将此SVG设置为div的背景图像。

是否有相同的SVG解决方案?或者可能如果有人知道如何在javascript中读取整个图像并将每个像素转换为灰度?

1 个答案:

答案 0 :(得分:0)

你的过滤器有些奇怪,可能会导致问题。您的过滤器应为:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 400 377" width="400px" height="377px">
  <defs>
     <filter id="filtersPicture">
       <feColorMatrix type="saturate" values="0"/>
    </filter>
  </defs>
  <image filter="url(#filtersPicture)" x="0" y="0" width="400" height="377"  xlink:href="whateverpathtoimage.jpg" />
</svg>