Question

I would like to use an image to control the alpha channel of a fill in SVG.

I can't figure out the right way to combine SourceGraphic with the alpha. Here is what I have right now:

<?xml version="1.0" encoding="UTF-8"?>
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" viewBox="0 0 300 300">
    <defs>
       <filter id="FILTER_pencil" primitiveUnits="userSpaceOnUse" filterUnits="objectBoundingBox" width="100%" height="100%">
         <feImage result="result1" width="128" height="128" xlink:href="http://lightartpixel.com/FILTER_pencil.png"/>
         <feColorMatrix type="luminanceToAlpha" result="alpha" in="result1"/>
         <feComposite operator="atop" in="alpha" in2="SourceGraphic"></feComposite>
       </filter>
     </defs>
     <rect fill="#5d496a" stroke="#5d496a" filter="url(#FILTER_pencil)" width="100" height="100"/>
  </svg>

Here is a jsfiddle that shows the current output. Which seems to be combining the luminance with the fill color.

Was it helpful?

Solution

You don't want to use atop, that renders both the black shape with variable opacity that you got from the luminanceToAlpha as well as the source graphic. Instead, you want to use the "in" operator, which only renders the source graphic, but uses the alpha values from the luminanceToAlpha as alpha. You also need to reverse the order of your "ins". This gets you what you want.

<feComposite operator="in" in2="alpha" in="SourceGraphic"></feComposite>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top