svgoutlinestroke

Outline a group of touching shapes with SVG


For a certain style I'm going for, I want to outline a group of shapes in SVG. Applied to a group, the stroke property appears to outline each shape individually--effectively going on top of other shapes nearby. To explain my situation more clearly: I have a group of touching rectangles that are 8x8 pixels each. They do not form a larger rectangle, however.

For simplicity's sake, let's say they form a cross. So I have 5 rectangles--1 in the center and one more on each side of that one. I want to outline them all as if they were 1 shape. Given that this "cross" shape changes, I would prefer not to use paths since that would require a lot more coding. Isn't there any way that I could get the effects filter to recognize this group as a single shape?

If not, is it at least possible to make a black copy of this group that's exactly 2px larger in width and height that I can position behind the group to create a solid black outline? And if so, is it possible without duplicating the group?

Thank you for any help.


Solution

  • Like this:

    <svg xmlns="http://www.w3.org/2000/svg">
        <defs>
            <filter id="biggerbwcopy">
              <feColorMatrix values="0 0 0 0 0
                                     0 0 0 0 0
                                     0 0 0 0 0
                                     0 0 0 1 0"/>
              <feMorphology operator="dilate" radius="2"/>
            </filter>
        </defs>
        <rect id="r" x="10" y="10" width="20" height="20" fill="blue" onclick="biggerbw()"/>
        <script>
    
          function biggerbw() {
            document.getElementById("r").style.filter="url(#biggerbwcopy)";
          }
        </script>
    </svg>
    

    http://jsfiddle.net/longsonr/LrDHT/1/ click on the rectangle and it becomes black and bigger.

    You could extend the filter to put the original shape on top using feMerge