IE10和IE11在图像滤镜方面还是比较坑爹的,不能执行filter滤镜,而且连svg滤镜也不支持,所以通常是用js来实现这个效果的。
具体可以参考下面这段代码:
var imgObj = document.getElementById('imgToGray')
function gray(imgObj) {
var canvas = document.createElement('canvas')
var canvasContext = canvas.getContext('2d')
var imgW = imgObj.width
var imgH = imgObj.height
canvas.width = imgW
canvas.height = imgH
canvasContext.drawImage(imgObj, 0, 0)
var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH)
for (var y = 0 y < imgPixels.height y++) {
for (var x = 0 x < imgPixels.width x++) {
var i = (y * 4) * imgPixels.width + x * 4
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3
imgPixels.data[i] = avg
imgPixels.data[i + 1] = avg
imgPixels.data[i + 2] = avg
}
}
canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height)
return canvas.toDataURL()
}
imgObj.src = gray(imgObj)
还有一些跨浏览器的解决方案,代码太多,不贴出来了,百度一下就能够找到。
利用SVG和滤镜分别实现:
<style type="text/css">img{
-webkit-filter: grayscale(100%)
-moz-filter: grayscale(100%)
-ms-filter: grayscale(100%)
-o-filter: grayscale(100%)
filter: grayscale(100%)
filter: url("data:image/svg+xmlutf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\' x=\'0\' y=\'0\' width=\'100%\' height=\'100%\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale")
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)
}
img:hover{
-webkit-filter: grayscale(0)
-moz-filter: grayscale(0)
-ms-filter: grayscale(0)
-o-filter: grayscale(0)
filter: grayscale(0)
filter: url("data:image/svg+xmlutf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\' x=\'0\' y=\'0\' width=\'100%\' height=\'100%\'><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")
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=0)
}
</style>