如何在 SVG 图形的特定边上设置 stroke-width:1?

107

在SVG中,将stroke-width: 1应用于<rect>元素会在矩形的每个边上放置描边。

那么怎样只在SVG矩形的三个边上放置描边呢?

3个回答

182
如果您需要描边或不描边,则可以使用stroke-dasharray来实现,方法是使矩形的虚线和空隙与矩形的边缘对齐。

rect { fill: none; stroke: black; }
.top { stroke-dasharray: 0,50,150 }
.left { stroke-dasharray: 150,50 }
.bottom { stroke-dasharray: 100,50 }
.right { stroke-dasharray: 50,50,100 }
<svg height="300">
    <rect x="0.5" y="0.5" width="50" height="50" class="top"/>
    <rect x="0.5" y="60.5" width="50" height="50" class="left"/>
    <rect x="0.5" y="120.5" width="50" height="50" class="bottom"/>
    <rect x="0.5" y="180.5" width="50" height="50" class="right"/>
</svg>

请查看 jsfiddle


我们如何只在矩形元素的顶部显示描边? - Suresh
2
你能解释一下为什么特定位置的某些数字会产生这种效果吗? - JacobIRR
@JacobIRR 参考“stroke-dasharray”属性的定义(在答案中链接)。这里的想法是将矩形的虚线长度与其边缘匹配,将虚线间隙与不应有描边的边缘匹配。 - Erik Dahlström
我刚刚更新了你的解决方案,在这个链接中 https://codepen.io/shaswatatripathy/pen/oNgPpyd - tripathy
这是一个编程解决方案,它根据定义哪些边框应该显示的对象生成 stroke-dasharray。阅读代码可能有助于您了解其工作原理:https://codepen.io/lazd/pen/WNweNwy?editors=1010 - lazd
您可以通过设置顶部、右侧+底部+左侧的虚线数组来仅描绘顶部。您可以通过设置0(不绘制任何内容)、顶部+右侧+底部、左侧的虚线数组来仅描绘左侧(例如)。换句话说,第一个数字绘制,第二个数字跳过绘制,接下来绘制,以此类推。通过使用jsfiddle进行调试,我成功地得到了我想要的效果(一个左边框)。 - moodboom

37
You cannot change the visual style of different parts of a single shape in SVG, except for the not-yet-available Vector Effects module. To achieve this, you need to create separate shapes for each stroke or other visual style that you want to vary.
For this particular case, instead of using a <rect> or <polygon> element, you can use a <path> or <polyline> that only covers three sides of the rectangle.
<!-- Move to 50,50 then draw a line to 150,50, to 150,150, and then to 50,150 -->
<path d="M50,50 L150,50 150,150 50,150" />
<polyline points="50,50 150,50 150,150 50,150" />

您可以在此处查看它们的实际效果:http://jsfiddle.net/b5FrF/3/

Red square with stroke on three sides

了解更多信息,请阅读关于<polyline>以及更强大但更令人困惑的<path>形状。


2

您可以使用折线来绘制三条描边边,而且完全不需要在矩形上绘制描边。我认为SVG不允许您对路径/形状的不同部分应用不同的描边,因此您需要使用多个对象才能获得相同的效果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接