Search code examples
svgsvg-filters

SVG mask using images only alpha channel


I'm trying to use an image for masking another SVG. I have a problem that the image has RGB and alpha channel so the masking is using both of the channel.

I've tried this for now:

<mask id="mask-1" maskUnits="userSpaceOnUse" x="0" y="0"
      width="1600" height="3200">
        <rect x="-92" y="-707.5" width="1600" height="3200"
        filter="url(#a)"></rect>
</mask>
<filter id="a">
      <feImage out="SourceAlpha" x="-92" y="-707.5" width="1600" height="3200"
        xlink:href="image.png"
        preserveAspectRatio="none" />
</filter>

But it doesn't give the desired output.

Any help?


Solution

  • You need to process the SourceAlpha some more because it has its luminance channels set to black - you want it set to white - so you'll need a colormatrix. (and you also need to use correct syntax and mechanics).

    This has the benefit of working in IE 10+ as well (where mask-type isn't supported yet.)

      <filter id="justAlphaandWhite">
          <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 1  0 0 0 0 1  0 0 0 0 1  0 0 0 1 0" />
       </filter>
    
        <mask id="m">
             <image filter="url(#justAlphaandWhite)" width="512" height="341.5" xlink:href="http://www.fnordware.com/superpng/pnggrad16rgba.png"/>
        </mask>
      </defs>
    
      <g mask="url(#m)">
              <circle cx="256" cy="200" r="150" fill="black"/>
      </g>