Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG filter with variable?

I have an SVG glow filter implemented like so:

<filter id="outline">
    <feMorphology in="SourceAlpha" operator="dilate" radius="2"></feMorphology>
    <feGaussianBlur stdDeviation="1" result="dilated"></feGaussianBlur>
    <feFlood style="flood-color: #RRGGBB"></feFlood>
    <feComposite in2="dilated" operator="in"></feComposite>
    <feMerge>
        <feMergeNode></feMergeNode>
        <feMergeNode in="SourceGraphic"></feMergeNode>
    </feMerge>
</filter>

This works nicely, but only for one specific glow colour.

I would like to be able to have an arbitrary glow colour, in some way passing a variable in to the flood-color property.

I have tried using currentColor, but this seems to be the colour as it is when the filter is defined, not when it is applied.

I could define a filter for each colour (there will be a limited number of them) but it would be nicer - and certainly more space-efficient - to only need to define it once. Is this possible and if so how?

like image 685
Niet the Dark Absol Avatar asked Nov 07 '22 16:11

Niet the Dark Absol


1 Answers

In the next example the flood-color is the current color. If you click the svg element you toggle the class "blue". The color of the svg element is red the color of the .blue is blue.

When you toggle the class blue the filter is changing the flood color.

test.addEventListener("click",()=>{
  test.classList.toggle("blue")
})
svg {
  border: 1px solid;
  font-size: 40px;
  text-anchor: middle;
  dominant-baseline: middle;
  width:100px;
  color:red;
}

.blue{color:blue;}
<svg id="test"  viewBox="0 0 100 70">
  
  <filter id="outline">
    <feMorphology in="SourceAlpha" operator="dilate" radius="2"></feMorphology>
    <feGaussianBlur stdDeviation="1" result="dilated"></feGaussianBlur>
    <feFlood style="flood-color: currentcolor"></feFlood>
    <feComposite in2="dilated" operator="in"></feComposite>
    <feMerge>
        <feMergeNode></feMergeNode>
        <feMergeNode in="SourceGraphic"></feMergeNode>
    </feMerge>
</filter>
  
<text x="50" y="40" filter="url(#outline)">click</text>
  
</svg>
like image 106
enxaneta Avatar answered Nov 12 '22 17:11

enxaneta