Search code examples
javascripthtmlcsssvgsvg-filters

Using a filter to add highlight-color glow to SVG?


I'm developing a SVG sketchpad and I would very much like to show an outline around the selected SVG object. I have the following already:

<svg width="0" height="0">
    <filter id="outline">
        <feMorphology operator="dilate" radius="1" in="SourceGraphic" result="glow" />
        <feComposite operator="over" in="glow" in2="SourceGraphic"></feComposite>
    </filter>
</svg>

path.selected { filter: url(#outline); }

This creates a hard pixel outline around the path but the "glow" is always the same color as the path. Can I use feColorMatrix to recolor it to the css highlight color? Is there any easier way?


Solution

  • You can add a feFlood to the filter and set the flood-color in css

    svg{color:red}
    feFlood{flood-color:currentColor;}
    <svg>
      <filter id="outline">
        <feMorphology in="SourceAlpha" result="expanded" operator="dilate" radius="1" />
        <feFlood result="color" />
        <feComposite in="color" in2="expanded" operator="in" />
        <feComposite in="SourceGraphic" />
      </filter>
    
      <rect x="10" y="10" width="100" height="50" fill="gold" filter="url(#outline)" />
    </svg>