Angular环境下Firefox带URL参数时SVG路径文字缺失问题咨询
问题成因
- 核心原因是Firefox 78版本对SVG锚点引用的解析逻辑与Chromium内核浏览器存在差异:当页面URL携带查询参数时,Firefox会将完整URL(包含查询参数部分)作为相对锚点的解析基准,你代码中写的
xlink:href="#p1"会被解析为http://localhost:4200?x=3#p1,无法匹配到页面内id为p1的path节点,textPath找不到绑定的路径导致文本无法渲染。 - Chromium内核浏览器解析相对锚点时会自动忽略查询参数,仅以页面基础路径作为基准,因此无论是否带参数都可以正常匹配节点,显示正常。
解决方案
直接将锚点引用修改为绑定不带查询参数的绝对路径锚点即可,修改后的代码如下:
import { Component, VERSION } from '@angular/core'; @Component({ selector: 'app-root', template: ` Version={{ver.full}} <hr/> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="300" width="300"> <path id="p1" fill="transparent" stroke="blue" d="M 100 100 A 100 100 0 0 0 200 200" stroke="blue"/> <text font-family="Verdana" font-size="20" fill="green" text-anchor="middle"> <textPath startOffset="50%" [attr.xlink:href]="pathHref">Hello there!</textPath> </text> </svg> ` }) export class AppComponent { ver = VERSION; // 拼接不带查询参数的绝对路径锚点 pathHref = `${window.location.origin}${window.location.pathname}#p1`; }
如果你的项目配置了<base>标签,也可以用base路径拼接:pathHref = ${document.querySelector('base').href}#p1``
也可以直接使用SVG 2标准支持的href属性替代xlink:href,兼容性适配Firefox 78版本没有问题:
<textPath startOffset="50%" [attr.href]="pathHref">Hello there!</textPath>
内容的提问来源于stack exchange,提问作者chris01
相关产品推荐
相关产品推荐

