如何在SVG路径内居中显示文本?修复textPath不显示问题
修复SVG textPath不显示文本的问题
问题背景
从后端获取路径数组构建自定义平面图,需要给每个路径添加可见且可编辑的中心名称,但当前代码中textPath部分无法显示文本。
原问题代码
<svg viewBox="0 0 2000 1024" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect width="2000" height="1024" fill="white"/> <rect x="930.5" y="0.5" width="139" height="570" fill="#D5D5D5" stroke="black"/> <ng-container *ngFor="let path of paths"> <path [attr.d]="path.d" [attr.stroke]="path.stroke" data-boutiqueId="path.boutiqueId"></path> <text style="font-size: 24px;"> <textPath [attr.href]="'#' + path.boutique.id" startOffset="50%" text-anchor="middle"> {{ path.boutique.id }} </textPath> </text> </ng-container> <rect x="1.5" y="1.5" width="1997" height="1021" stroke="black" stroke-width="3"/> <defs> <clipPath id="clip0_103_2"> <rect width="2000" height="1024" fill="white"/> </clipPath> </defs> </svg>
核心问题与修复步骤
1. 路径元素缺少id属性
textPath的href是通过# + path.boutique.id关联对应路径的,但原代码中的<path>标签没有设置id,导致textPath找不到目标路径。需要给路径添加id属性:
<path [attr.id]="path.boutique.id" [attr.d]="path.d" [attr.stroke]="path.stroke" [attr.data-boutiqueId]="path.boutiqueId"></path>
2. 文本缺少填充颜色
<text>元素默认fill为none,即使textPath关联正确,文本也会因没有颜色而不可见。需要给<text>添加填充颜色,比如使用和路径相同的颜色:
<text style="font-size: 24px;" [attr.fill]="path.stroke">
3. 可选优化(针对闭合路径)
如果路径是闭合图形,textPath可能无法正常居中显示,此时可以考虑将路径转换为非闭合,或者使用<text>结合路径的边界框计算中心位置。完成前两步即可解决基础显示问题。
修复后的完整代码
<svg viewBox="0 0 2000 1024" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect width="2000" height="1024" fill="white"/> <rect x="930.5" y="0.5" width="139" height="570" fill="#D5D5D5" stroke="black"/> <ng-container *ngFor="let path of paths"> <!-- 新增id属性,关联textPath的href --> <path [attr.id]="path.boutique.id" [attr.d]="path.d" [attr.stroke]="path.stroke" [attr.data-boutiqueId]="path.boutiqueId"></path> <!-- 添加fill属性确保文本可见 --> <text style="font-size: 24px;" [attr.fill]="path.stroke"> <textPath [attr.href]="'#' + path.boutique.id" startOffset="50%" text-anchor="middle"> {{ path.boutique.id }} </textPath> </text> </ng-container> <rect x="1.5" y="1.5" width="1997" height="1021" stroke="black" stroke-width="3"/> <defs> <clipPath id="clip0_103_2"> <rect width="2000" height="1024" fill="white"/> </clipPath> </defs> </svg>
内容的提问来源于stack exchange,提问作者Kraken TV
相关产品推荐
相关产品推荐

