在 svg 中用透明路径重叠彩色矩形/在与路径的交叉点上打破矩形填充颜色

Overlapping a colored rect with transparent path in a svg / breaking rect fill color on the intersection with a path

我有一个与以下类似的代码,由动态内容创建工具生成,即该工具的用户将根据需要选择颜色。问题出现在矩形是彩色的,但是路径内部是透明的,所以矩形的颜色会填满路径里面的所有部分。目标是显示矩形应有的颜色,但避免在透明路径的内部着色,而是可以显示该透明部分后面的潜在对象。

    <svg xmlns="http://www.w3.org/2000/svg"  style="position: absolute;" id="id2_svg" >
    <g id="id2_g" >
    <rect id="id2_rect" style="fill:rgba(255 , 255 , 0 , 255);"  />
    <path id="id2_path" d="M 32.0 2.0 C 6.0 -2.0 -10.0 71.0 13.0 89.0 C 36.0 107.0 168.0 125.0 171.0 111.0 C 174.0 96.0 58.0 6.0 32.0 2.0" style=  "fill: #fff; fill-opacity: 0;  pointer-events: visiblePainted" />
    </g>
    </svg>

在路径样式中使用任何填充值都会产生相同的结果。使用stroke可以保持路径内部确定,但背景为黑色!

OP 正在添加此评论:

Is there any way to break the fill of the rect in the intersection with the path?

您可以像这样剪裁矩形:

   <svg viewBox="0 0 300 150" >
    <defs>
      <clipPath id="clip">
      <path id="id2_path" d="M 32.0 2.0 C 6.0 -2.0 -10.0 71.0 13.0 89.0 C 36.0 107.0 168.0 125.0 171.0 111.0 C 174.0 96.0 58.0 6.0 32.0 2.0"  />
      </clipPath>
    </defs>
    <g id="id2_g" >
    <rect id="id2_rect" style="fill:rgba(255 , 255 , 0 , 255);" width="100" height="100" clip-path="url(#clip)" />
    <use xlink:href="#id2_path" stroke="black" fill="none"/>
    </g>
    </svg>

OP 正在评论:

Actually what I want is the inverse of this. By using clip path, I clip the outside of the path i.e. like making it transparent but what I want is to clip inside the path and make it transparent while keeping the color of the rest of the rectangle as it is. Anyway thanks for your answer !

在这种情况下,我建议使用修改后的路径。对于原始 d 属性,我将添加:M0,0H300V150H0V0z。我希望这是你需要的。

  <svg viewBox="0 0 300 150" >
    <defs>
      <clipPath id="clip">
      <path id="id2_path" d="M 32.0 2.0 C 6.0 -2.0 -10.0 71.0 13.0 89.0 C 36.0 107.0 168.0 125.0 171.0 111.0 C 174.0 96.0 58.0 6.0 32.0 2.0
      M0,0H300V150H0V0z"  />
      </clipPath>
    </defs>
    <g id="id2_g" >
    <rect id="id2_rect" style="fill:rgba(255 , 255 , 0 , 255);" width="100" height="100" clip-path="url(#clip)" />
    <path id="id2_path" d="M 32.0 2.0 C 6.0 -2.0 -10.0 71.0 13.0 89.0 C 36.0 107.0 168.0 125.0 171.0 111.0 C 174.0 96.0 58.0 6.0 32.0 2.0" stroke="black" fill="none" />
    </g>
    </svg>

更新:

This should help me but can you explain in details why you have added this to the original path

通过将 M0,0H300V150H0V0z 添加到路径中,您可以绘制一个与 svg 一样大的矩形 canvas 以相反的方式绘制矩形。在这种情况下,您从左到右绘制路径,从右到左绘制添加的矩形。这样你就创建了一个带孔的矩形,你正在使用这个形状作为 clipPath:

添加字符串的模拟:M0,0H300V150H0V0z

  • 移动到 svg 的原点 canvas M0,0

  • 从上一点到点{300,0}的水平线H300

  • 从上一点到点{300,150}的垂直线V150

  • 从上一点到点 {0,150} 的水平线 H0

  • 从上一点到点 {0,0} 的垂直线 V0

  • 关闭路径:z

<svg viewBox="0 0 300 150" >
<path id="id2_path" d="M 32.0 2.0 C 6.0 -2.0 -10.0 71.0 13.0 89.0 C 36.0 107.0 168.0 125.0 171.0 111.0 C 174.0 96.0 58.0 6.0 32.0 2.0  M0,0H300V150H0V0z"  />
</svg>

And why you added again the original path points inside the <g> tag.

因为现在用于 clipPath 的路径看起来与添加的字符串不同。