【问题标题】:SVG marker-end only appears when not dynamically created (innerHTML = innerHTML)SVG marker-end 仅在未动态创建时出现(innerHTML = innerHTML)
【发布时间】:2021-05-21 15:26:58
【问题描述】:

这是一个非常了不起的错误,我仍然不确定如何解决它。慈善的解释是我弄错了document.createElementNS 的语义,而不那么慈善的是每个主流浏览器都有一个错误。我希望是前者。

当使用url(#id) 引用<marker> 动态创建带有marker-end 的SVG 路径时,marker-end 不会呈现。但是,相同 HTML 源代码在一次性插入时可以正确呈现。请参阅以下示例。当您按下“让它变好”按钮时,唯一运行的代码是: svg.innerHTML = svg.innerHTML!如您所见,箭头仅在单击按钮时出现。

const elem = document.createElementNS("http://www.w3.org/2000/svg", "g");

const id = `arrowhead_2`;

const marker = document.createElementNS(
    "http://www.w3.org/2000/svg",
    "marker"
  );
marker.setAttribute("id", id);
marker.setAttribute("markerUnits", "strokeWidth");
marker.setAttribute("markerWidth", "6.97");
marker.setAttribute("markerHeight", "5.68");
marker.setAttribute("viewBox", "0 0 9.95 8.12");
marker.setAttribute("refX", "2.36");
marker.setAttribute("refY", "4.06");
marker.setAttribute("orient", "auto-start-reverse");
const path = document.createElementNS("svg", "path");
path.setAttribute("d", "M9.95 4.06 0 8.12 2.36 4.06 0 0 9.95 4.06z");
path.setAttribute("fill", "#00cc00");
path.setAttribute("fill-opacity", "1");
marker.appendChild(path);

const arrow = document.createElementNS("http://www.w3.org/2000/svg", "g");
arrow.appendChild(marker);

const arrowPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
arrowPath.setAttribute("d", "M0 10 L10.0981265193531 28.49209939676484");
arrowPath.setAttribute("marker-end", `url(#${id})`);
arrowPath.setAttribute("fill", "#00cc00");
arrowPath.setAttribute("fill-opacity", "1");
arrowPath.setAttribute("stroke", "#00cc00");
arrowPath.setAttribute("stroke-width", "3");

arrow.appendChild(arrowPath);

const svg = document.getElementById("mysvg");
svg.appendChild(arrow);

document.getElementById("makegood").onclick = () => {
    svg.innerHTML = svg.innerHTML; 
};
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
</head>
<body>
  <button id="makegood">make it good</button>
<svg
    id="mysvg"
        width="100%"
        height="100%"
        version="1.2"
        viewBox="0 0 100 100"
        xmlns="http://www.w3.org/2000/svg"
      ></svg>
</html>

感谢您的帮助!

【问题讨论】:

  • document.createElementNS("svg", "path"); “svg”不是有效的命名空间。您可以在文档中更早和更晚地得到它。
  • 天啊,谢谢@RobertLongson

标签: javascript svg dom


【解决方案1】:

cmets 中的 Robert 成功了,这就是路线

const path = document.createElementNS("svg", "path");

实际上应该是

const path = document.createElementNS("http://www.w3.org/2000/svg", "path");

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2016-05-17
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多