Home > Blockchain >  How to make a transparent marging in SVGs
How to make a transparent marging in SVGs

Time:12-17

Assume I have two circles in a SVG that overlap

like this

<svg height="100" width="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="20" fill="#ffffff" />
  <circle cx="50" cy="40" r="20" stroke="none" stroke-width="2" fill="#ffffff"/>
</svg>

Now as you can see I have some margin in one circle (stroke resp. stroke-width). However, that margin does not show off, because there is the other circle and it should be completely "empty". Here, everything is as desired with blue color

<svg height="100" width="100" xmlns="http://www.w3.org/2000/svg">
  <rect width="100" height="100" x="0" y="0" fill="blue"/>
  <circle cx="50" cy="50" r="20" fill="#ffffff" />
  <circle cx="50" cy="40" r="20" stroke="blue" stroke-width="2" fill="#ffffff"/>
</svg>

the only difference is the nothing should be blue, but just the "unmarked"/transparent territory.

Do you know how to make that happen?

CodePudding user response:

Without adding stroke, you can use CSS filter drop-shadow to show that circle.

.cls {
       filter: drop-shadow(0px 0px 1px rgb(0, 0, 0, 0.7));
  }
<svg height="100" width="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="20"  fill="#fff" />
  <circle cx="50" cy="40" r="20"  stroke="none" fill="#fff"/>
</svg>

CodePudding user response:

You can use a mask so that the stroke apears like if it was transparent. In fact it's a hole.

svg {
  background: url("https://assets.codepen.io/222579/darwin300.jpg");
  background-size: 100px 100px;
}
<svg height="100" width="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="20" fill="#ffffff" mask="url(#m)"/>
  <circle id="c2" cx="50" cy="40" r="20" stroke-width="2" fill="#ffffff"/>
  <mask id="m">
    <rect height="100" width="100" fill="white"/>
    <use xlink:href="#c2" stroke="black"/>
  </mask>  
</svg>

CodePudding user response:

You can create a mask that makes it look like the stroke is transparent. So, the mask will only show the part of the circle that is not covered by the stroke (if that makes sense...).

Be aware that a stroke both cover inside and outside the outline of a circle. You can see that I use a circle with radius 21 so that the "distance" between the two shapes is 2.

<svg viewBox="0 0 100 100" width="300"
  xmlns="http://www.w3.org/2000/svg">
  <defs>
    <mask id="m1">
      <rect width="100" height="100" fill="white"/>
      <circle cx="50" cy="40" r="21" stroke-width="2"
        fill="white" stroke="black" />
    </mask>
  </defs>
  <rect width="100" height="100" x="0" y="0" fill="blue" />
  <circle cx="50" cy="50" r="20" fill="white" stroke="none"
    mask="url(#m1)" />
  <circle cx="50" cy="40" r="20" fill="white" stroke="none" />
</svg>

  • Related