从svg切割出来的物品

时间:2018-05-17 20:43:01

标签: svg cut

我的图像中间的紫色必须是透明的。在那紫色的背后,黄色只是继续通过它不起作用。

是否可以将紫色切成黄色以使其变得透明?如果是这样,谁知道这个工具?

问候

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

1 个答案:

答案 0 :(得分:2)

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

<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>

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

要透过黄色矩形,我们需要在其中切出一个与紫色元素具有相同形状的洞。我们可以使用面具来做到这一点。

<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>

请注意,我暂时删除了紫色矩形,以便我们可以看到正在发生的事情。

如果我们现在重新加入,我们将得到最终结果。

<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>元素在两个地方引用它。

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