如何在 SVG 中剪出虚线?

  • 本文关键字:虚线 SVG svg
  • 更新时间 :
  • 英文 :


下面是一个例子:

<svg width="200" height="200">
<rect x="50" y="50" width="100" height="100"/>
<line x1="0" y1="0" x2="200" y2="200" stroke="red" stroke-width="5" stroke-dasharray="5"/>
</svg>

https://codepen.io/anon/pen/oyqYKZ

我希望从矩形中剪出红线,以便矩形上有红色破折号的地方应该有孔。

我尝试使用clipPath:https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Clipping_and_masking。但这似乎只是削减了"填充"而不是笔触。

你需要的是一个面具。

对于面具来说,颜色很重要。想象一下,蒙版元素的内容被转换为灰度。然后,白色将使蒙版内容完全不透明,黑色为零不透明度,灰色介于部分不透明度之间。空白区域被视为黑色 = 透明。因此,蒙版必须包含白色背景和前景中的黑色虚线。

<svg width="200" height="200">
<mask id="dash">
<rect width="100%" height="100%" fill="white"/>
<line x1="0" y1="0" x2="200" y2="200" stroke="black" stroke-width="5" stroke-dasharray="5"/>
</mask>
<rect x="50" y="50" width="100" height="100" mask="url(#dash)"/>
</svg>

最新更新