SVG shape transparency with solid color as a background

夙愿已清 提交于 2019-12-08 17:43:47

问题


I have an svg container which I used as a background, and inside it a circle is drawn

basically, this is what I've done:

<svg width="200" height="200" style="background-color:green">
    <circle cx="100" cy="100" r="80" stroke="black" stroke-width="2" fill="transparent" />
</svg>

it creates something like this

You can see the circle is transparent but it still has the green background from the svg tag, how can I make the circle really transparent so it can appear as a hole (in this case it will be white since the page background is white), to make it clear this is what I want to display:

Is there any way that can make this happen?


回答1:


You could use a mask. Here you can see the red background cut through the rect.

<svg width="200" height="200" style="background-color:red">
    <mask id="mask">
        <rect fill="white" width="100%" height="100%"/>
        <circle cx="100" cy="100" r="80" stroke="black" stroke-width="2" fill="black" />
    </mask>
    <rect mask="url(#mask)" fill="green" width="100%" height="100%"/>
</svg>



回答2:


I've added visible example of @Rober solution

.svgClass {
  position: absolute;
  top: 0;
}
<div>
  The text should be visible within the circle
</div>

<div class="svgClass">
  <svg width="100%" height="100%" >
    <mask id="mask">
      <rect fill="white" width="100%" height="100%" fill-opacity="1" />
      <circle cx="100" cy="100" r="90" />
    </mask>
    <rect mask="url(#mask)" fill="green" width="100%" height="100%" fill-opacity="1"/>
  </svg>
</div>


来源:https://stackoverflow.com/questions/26462205/svg-shape-transparency-with-solid-color-as-a-background

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!