如何反转SVG的Alpha通道

时间:2019-04-08 22:57:32

标签: css svg svg-filters

svg image

我有这样的SVG图片。我想将其反转,以使所有黑色的物体变为透明,而所有透明的物体变为黑色。因此,结果将是一个黑色的正方形,中间有一个透明的正方形“孔”。我该如何实现?

svg的代码:

<svg
   xmlns="http://www.w3.org/2000/svg"
   viewBox="0 0 99.999997 99.999997"
   height="100"
   width="100">
  <g
     transform="translate(0,-952.36223)"
  >
    <path
       d="M 50.000001,954.80939 65.450848,986.11624 100,991.13652 74.999998,1015.5055 80.901699,1049.915 50,1033.6691 19.098298,1049.915 25.000001,1015.5055 -1.2134336e-6,991.13652 34.549151,986.11624 Z"
       style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:22.67716599;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
  </g>
</svg>

2 个答案:

答案 0 :(得分:4)

将路径用作mask,如下所示:

body {
  background:pink;
}
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"
   viewBox="0 0 99.999997 99.999997">
  <defs>
    <mask id="hole">
      <rect width="100%" height="100%" fill="white"/>
      <path transform="translate(0,-952.36223)"
       d="M 50.000001,954.80939 65.450848,986.11624 100,991.13652 74.999998,1015.5055 80.901699,1049.915 50,1033.6691 19.098298,1049.915 25.000001,1015.5055 -1.2134336e-6,991.13652 34.549151,986.11624 Z"
       fill="black" />
    </mask>
  </defs>
  <rect fill="black" width="100%" height="100%" mask="url(#hole)" />
</svg>

答案 1 :(得分:2)

您可以使用feComponentTransfer过滤器反转Alpha通道。这样可以完全反转(又称-20%的不透明度将变为80%的不透明度)。

<svg
   xmlns="http://www.w3.org/2000/svg"
   viewBox="0 0 99.999997 99.999997"
   height="100"
   width="100">
  <defs>
    <filter id="invert-alpha">
      <feComponentTransfer>
        <feFuncA type="table" tableValues="1 0"/>
      </feComponentTransfer>
    </filter>
  </defs>
  <g
     transform="translate(0,-952.36223)" filter="url(#invert-alpha)"
  >
    <path
       d="M 50.000001,954.80939 65.450848,986.11624 100,991.13652 74.999998,1015.5055 80.901699,1049.915 50,1033.6691 19.098298,1049.915 25.000001,1015.5055 -1.2134336e-6,991.13652 34.549151,986.11624 Z"
       style="opacity:1;fill:#000000;fill-opacity:1;stroke:none;stroke-width:22.67716599;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
  </g>
</svg>