Monday, September 9, 2013

Using SVG Filters to Create Outlines of Shapes

I needed a quick way to add an outline around an SVG shape without having to create one for all the shapes I was using. I knew I could use a filter for a drop shadow effect so figured that there must be something that could make this possible.

I finally found the solution using the dilate operator of the feMorphology filter. This made a copy of the object and expanded out a certain radius. Next, I remapped all the colors so the expanded shape was yellow. I blended that behind the original shape to produce my outline:

Apply it to any shape to create a yellow outline around it:


That seemed pretty easy except when you'd like to have more control of the color of the outline. Using the feColorMatrix to remap the input shape's color to a single color that will represent the outline is somewhat difficult. If you want simple primary colors, you're probably fine. Outside of that, and its not as easy.

A better approach, even if it uses more operators, is to start with a feFlood which will represent the color of the outline. The trick from there is to take the resulting filled rectangle that filter makes and, essentially, cut out the the slightly enlarged shape to form the outline. I accomplished this by using the feMorphology filter to create the bigger version of the shape, map that through feColorMatrix to make it black, and use feComposite to take that mask and "cut out" the section of the flood fill I wanted to keep. The resulting shape can be blended back with the original to create the outline effect:


And, if you want to make it glow, add a blur effect:


Its now a lot easier to change the color of the outline by just adjusting the value of flood-color in the feFlood filter operator. After composing the outline from the flood fill and morphed shape, you can apply more filters to create more effects. I've added a demo on my sandbox which allows you to change the colors of both the shape and outline interactively.