首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从svg中剪切对象

从svg中剪切对象
EN

Stack Overflow用户
提问于 2018-05-18 04:43:01
回答 1查看 169关注 0票数 0

我有一张图片,中间的紫色必须是透明的。在紫色后面,黄色只是继续,它不起作用。

有没有可能从黄色中切出紫色,使其变得透明?如果是这样,谁知道有什么工具可以做到这一点呢?

问候

https://media.scoutwiki.org/images/c/c3/Badge_Scouting_Nederland.svg

EN

回答 1

Stack Overflow用户

发布于 2018-05-18 14:19:49

让我们从SVG的简化版本开始。我将使用矩形作为你的两个形状的替身。

代码语言:javascript
运行
复制
<svg width="300" height="300">

  <text x="0" y="100">There is some sectret text hiding behind here!</text>
  <rect id="shamrock" fill="gold" x="0" y="0" width="300" height="200"/>
  <rect id="fleur-de-lis" x="50" y="50" width="200" height="250" fill="purple" opacity="0.5"/>

</svg>

请注意,我已经在黄色形状后面隐藏了一些文本,它现在已经被覆盖。此外,您还可以通过半透明的紫色矩形看到黄色矩形。

为了看透黄色的矩形,我们需要在它上面切一个与紫色元素形状相同的洞。我们可以使用口罩来实现。

代码语言:javascript
运行
复制
<svg width="300" height="300">

  <defs>
    <mask id="fleur-de-lis-mask">
      <rect width="100%" height="100%" fill="white"/>             <!-- white means "keep these parts" -->
      <rect x="50" y="50" width="200" height="250" fill="black"/> <!-- black represents the part that is the hole -->
    </mask>
  </defs>

  <text x="0" y="100">There is some sectret text hiding behind here!</text>
  <rect id="shamrock" fill="gold" x="0" y="0" width="300" height="200" mask="url(#fleur-de-lis-mask)"/>

</svg>

请注意,我临时删除了紫色矩形,这样我们就可以看到发生了什么。

如果我们现在把它放回去,我们就会得到最终的结果。

代码语言:javascript
运行
复制
<svg width="300" height="300">

  <defs>
    <rect id="fleur-de-lis-shape" x="50" y="50" width="200" height="250"/>
    
    <mask id="fleur-de-lis-mask">
      <rect width="100%" height="100%" fill="white"/>      <!-- white means "keep these parts" -->
      <use xlink:href="#fleur-de-lis-shape" fill="black"/> <!-- black represents the part that is the hole -->
    </mask>
  </defs>

  <text x="0" y="100">There is some sectret text hiding behind here!</text>
  <rect id="shamrock" fill="gold" x="0" y="0" width="300" height="200" mask="url(#fleur-de-lis-mask)"/>
  <use id="fleur-de-lis" xlink:href="#fleur-de-lis-shape" fill="purple" opacity="0.5"/>

</svg>

请注意,我们需要使用紫色形状两次:一次作为自身,一次在掩码中。为了使文件更小,我们可以在<defs>部分定义一次形状,然后使用<use>元素在两个位置引用它。

对于一个矩形,这似乎有点不必要,但如果你的形状是一个复杂的路径,这可能是一个很好的空间节省。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50400217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档