How do I use the luminance in an image to control the opacity of a fill in SVG

StackOverflow https://stackoverflow.com/questions/22337685

  •  13-06-2023
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top