invert SVG clip (show only outside path)

2020-05-30 03:24发布

问题:

Is it possible to invert the action of a clip with SVG? In the example below I would like to show the path between the two circles rather than inside the circles:

<svg xmlns="http://www.w3.org/2000/svg" width="985" height="740">
  <g>
    <clipPath id="re8-clip" clip-rule="nonzero">
      <rect id="sa11" x="763.0" y="176.5" width="70.0" height="25.0" rx="50" ry="50" fill="ForestGreen"/>
      <rect id="sa12" x="516.0" y="127.5" width="70.0" height="25.0" rx="50" ry="50" fill="ForestGreen"/>
    </clipPath>
    <rect id="sa11" x="763.0" y="176.5" width="70.0" height="25.0" rx="50" ry="50" fill="ForestGreen"/>
    <rect id="sa12" x="516.0" y="127.5" width="70.0" height="25.0" rx="50" ry="50" fill="ForestGreen"/>
  </g>
  <path stroke="Black" stroke-width="1.5" fill="none" d="M 798.0 189.0 551.0 140.0" clip-path="url(#re8-clip)"/>
</svg>

回答1:

Following the link in Duopixel's comment, the problem can be solved using a mask:

<svg width="50%" height="50%" viewbox="0 0 985 740" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <rect id="sa11" x="763.0" y="176.5" width="70.0" height="25.0" rx="50" ry="50" />
    <rect id="sa12" x="516.0" y="127.5" width="70.0" height="25.0" rx="50" ry="50" />
  </defs>
  <mask id="re8-clip">
    <rect id="bg" x="0" y="0" width="100%" height="100%" fill="white"/>
    <use xlink:href="#sa11" fill="Black" />
    <use xlink:href="#sa12" fill="Black" />
  </mask>
  <use xlink:href="#sa11" fill="ForestGreen" />
  <use xlink:href="#sa12" fill="ForestGreen" />
  <path stroke="Black" stroke-width="1.5" fill="none" d="M 798.0 189.0 551.0 140.0" mask="url(#re8-clip)"/>
</svg>

As a minor aside, does anybody know if it is possible for a mask to default to white, so the 'bg' rectangle is not necessary?



标签: svg