如何实现SVG椭圆上下中心位置的垂直边缘缺口?
解决方案
方法一:用<path>绘制分段椭圆(精确无误差)
直接绘制椭圆的左右两段弧,避开上下中心的垂直缺口,缺口边缘天然垂直,且不会遮挡背景。
<svg width="30" height="30" viewBox="0 0 30 30"> <g stroke="black" stroke-width="1.5" fill="none"> <!-- 右侧弧:连接顶部右侧缺口点到底部右侧缺口点 --> <path d="M15.75 1.58 A12.55 13.45 0 0 1 15.75 28.42"/> <!-- 左侧弧:连接底部左侧缺口点到顶部左侧缺口点 --> <path d="M14.25 28.42 A12.55 13.45 0 0 1 14.25 1.58"/> </g> </svg>
- 缺口宽度设为
1.5(和stroke-width一致),对应x坐标15±0.75 - 椭圆上的坐标通过椭圆方程计算得出,确保路径完全贴合原椭圆轮廓
- 两段弧分别对应椭圆的左右两侧,上下缺口为未绘制区域,不会覆盖背景
方法二:用stroke-dasharray调整(代码更简洁)
通过计算椭圆周长,设置合适的虚线数组和偏移量,配合stroke-linecap="square"实现垂直缺口。
<svg width="30" height="30" viewBox="0 0 30 30"> <ellipse fill="none" stroke="black" stroke-width="1.5" cx="15" cy="15" rx="12.55" ry="13.45" stroke-dasharray="39.36 1.5 39.36 1.5" stroke-dashoffset="19.68" stroke-linecap="square"/> </svg>
stroke-dasharray:39.36是椭圆半周长减去缺口长度(1.5),1.5是缺口宽度stroke-dashoffset:调整偏移量让缺口精准落在上下中心位置stroke-linecap="square":强制缺口边缘为垂直方形,解决你之前用dasharray时边缘不垂直的问题
内容的提问来源于stack exchange,提问作者jamacoe
相关产品推荐
相关产品推荐

