【问题标题】:SVG textpath element renders incorrectly in Firefox when generated using Javascript使用 Javascript 生成时,SVG 文本路径元素在 Firefox 中呈现不正确
【发布时间】:2014-08-16 13:12:21
【问题描述】:

以下代码在 Chrome、IE11 和 Opera 中呈现良好,但在 Firefox 中显示左上角的文本:

var svgNS = "http://www.w3.org/2000/svg";
var xlinkNS = "http://www.w3.org/1999/xlink";

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttributeNS(null, "viewBox", "0 0 1000 1000");
svg.id = "clockSVG";
document.body.appendChild(svg);

var defs = document.createElement('defs');
defs.id = "defs";
svg.appendChild(defs);

var path = document.createElementNS(svgNS,"path");
path.setAttribute("d","M75,20 l100,0 l100,30 q0,100 150,100");
path.setAttribute("id","myTextPath2");
defs.appendChild(path);

var text = document.createElementNS(svgNS,"text");
text.setAttribute("x","10");
text.setAttribute("y","100");
text.setAttribute("fill","black");
svg.appendChild(text);

var textPath = document.createElementNS(svgNS,"textPath");
textPath.setAttributeNS(xlinkNS, "xlink:href", "#myTextPath2");
textPath.textContent = "Text along a more advanced path with lines and curves.";
text.appendChild(textPath);
svg.appendChild(text);

如果我调用 text.getBBox(),它显示它拥抱左屏幕边缘并以某种方式接收负 y 值:

SVGRect { x: 0, y: -14.825797080993652, width: 355.164306640625, height: 18.532245635986328 }

经过一些实验,我发现要在 Firefox 中正确呈现在 HTML 中声明的 textPath 元素,textPath 元素的内容必须与标签在同一行。

这将呈现一个奇怪的偏移:

<text x="10" y="100" style="stroke: #000000;">
    <textPath xlink:href="#myTextPath2">
        Text along a more advanced path with lines and curves.
    </textPath>
</text>

这将正确呈现:

<text x="10" y="100" style="stroke: #000000;">
    <textPath xlink:href="#myTextPath2">Text along a more advanced path with lines and curves.</textPath>
</text>

(如果文本的 x 和 y 属性设置为 0 或留空,则它会正确呈现)

所以我尝试将必要的 HTML 构造为单行字符串并插入:

var textPathString = '<textPath xlink:href="#myTextPath2">Text along a more advanced path with lines and curves.</textPath>';
text.innerHTML = textPathString;

不幸的是,这不会渲染任何东西(在 Chrome 中也不起作用)。

如何确保 Firefox 正确显示由 JavaScript 生成的文本路径?

这些是错误吗?我应该报告它们吗?

我们将不胜感激任何和所有帮助,因为我的项目依赖于能够动态生成文本路径!

【问题讨论】:

  • textPath (bugzilla.mozilla.org/…) 是,innerHTML 不是(这是一个已知问题)
  • 谢谢,我已经提交了这个错误。与此同时,我想我必须找到一种解决方法来预先生成 HTML。
  • Alice 发现问题是 createElement("defs") 应该是 createElementNS。如果在修复之后还有另一个错误,那么请提出另一个错误,而不是重新打开您已经提出的错误。
  • 很好看!不敢相信我一直在为此而努力。非常感谢您的帮助!如果您将您的解决方案作为此问题的答案发布,我会将其标记为正确答案。

标签: javascript html firefox svg


【解决方案1】:

你写的是createElement("defs")而不是createElementNS,你在其他地方都用过。

【讨论】:

    猜你喜欢
    • 2014-08-14
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2014-12-05
    • 2021-03-12
    • 2023-02-09
    • 2018-08-18
    • 2019-10-16
    相关资源
    最近更新 更多