leo
leo

Reputation: 8520

Create outline for adjacent shapes

Given some bordering SVG shapes, is there any way to style them to have a border on their outer edges only?

Given an SVG like this:

<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="50" height="50" stroke="black" fill="#cccc99"/>
  <rect x="60" y="10" width="50" height="50" stroke="black" fill="#cccc99"/>
  <rect x="10" y="60" width="50" height="50" stroke="black" fill="#cccc99"/>
</svg>

enter image description here

I would like to have a border around the outer edge of the three adjacent rectangles. Is this possible using styles only? The shapes I work with are relatively simple (no holes or weird geometries), and bordering shapes will share exactly the same borders.

Upvotes: 0

Views: 146

Answers (1)

leo
leo

Reputation: 8520

As I set up a JSFiddle to create a picture for the question, I also came up with a possible solution. It does require some editing of the SVG (duplicating shapes), and it's not very forgiving with more complex shapes, but good enough for me, and I don't have to merge the shapes.

<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <filter id="dilate">
      <feMorphology operator="dilate" in="SourceGraphic" radius="2" />
    </filter>
    </defs>
  <rect x="10" y="10" width="50" height="50" fill="none" stroke-width="5" stroke="black"/>
  <rect x="10" y="60" width="50" height="50" fill="none" stroke-width="5" stroke="black"/>
  <rect x="60" y="10" width="50" height="50" fill="none" stroke-width="5" stroke="black"/>
  <rect x="10" y="10" width="50" height="50" fill="#cccc99" filter="url(#dilate)"/>
  <rect x="60" y="10" width="50" height="50" fill="#cccc99" filter="url(#dilate)"/>
  <rect x="10" y="60" width="50" height="50" fill="#cccc99" filter="url(#dilate)"/>
 </svg>

Shapes with common outer border

Fiddle: https://jsfiddle.net/rye2vfpz/

Here all shapes are duplicated, with the bottom-most layer providing the stroke, and the top-most providing the fill. I then use a dilate filter to let the fill cover the strokes from opposing sides. As long as the stroke is more than twice as thick as the dilution, only the outer strokes will be visible. Fiddle around with dilution radius and stroke width until you have the wanted effect.

Upvotes: 1

Related Questions