SVG filters feColorMatrix
feColorMatrix
The SVG filter element changes colors based on a transformation matrix. Every pixel’s color value [R,G,B,A] is matrix multiplied by a 5 by 5 color matrix to create new color [R’,G’,B’,A’].
| R' | | r1 r2 r3 r4 r5 | | R |
| G' | | g1 g2 g3 g4 g5 | | G |
| B' | = | b1 b2 b3 b4 b5 | * | B |
| A' | | a1 a2 a3 a4 a5 | | A |
| 1 | | 0 0 0 0 1 | | 1 |
R' = r1*R + r2*G + r3*B + r4*A + r5
G' = g1*R + g2*G + g3*B + g4*A + g5
B' = b1*R + b2*G + b3*B + b4*A + b5
A' = a1*R + a2*G + a3*B + a4*A + a5
这不就是 webgl里面的 片元着色器 吗,所以操作空间很大。再加上feTurbulence 噪声滤镜,越来越有搞头。
下面这个网站对各种svg滤镜做了一个可视化展示,方便理解和运用。
https://yoksel.github.io/svg-filters/#/
<svg style="width: 0; height:0">
<filter id="colorMatrix">
<feColorMatrix type="matrix" values="
1 0 0 0 0
1 0 0 0 0
0 0 0 0 0
0 0 0 1 0" />
</filter>
</svg>
<div style="filter: grayscale(1) url('#colorMatrix');">
<image style=" width: 200px;" src="./fox.png" alt="">
<image style=" width: 200px;" src="./lock.svg" alt="">
<image style=" width: 200px;" src="./soc.png" alt="">
</div>
<script>
var filter = document.querySelector('filter');
var feColorMatrix = document.createElementNS('http://www.w3.org/2000/svg', 'feColorMatrix');
feColorMatrix.setAttribute('type', 'matrix');
setInterval(() => {
feColorMatrix.setAttribute('values', `${0.25 + Math.random() * 0.75} 0 0 0 0 0 ${0.25 + Math.random() * 0.75} 0 0 0 0 0 0 0 0 0 0 0 1 0`);
filter.innerHTML = feColorMatrix.outerHTML;
}, 100);
</script>