36

再会,

我在创建路径并在 SVG 元素中使用“appendChild”显示它时遇到了难以置信的困难。

我必须遗漏一些非常简单的东西,因为我已经倾注了 W3C 的规范、w3schools.com、这里的各种帖子并试图以各种方式忍者谷歌。

我在 FireFox 和 Chrome 中进行测试。

我有一个简单的 svg 文件,因此:

<svg xmlns:svg ... id="fullPageID">
 <image id="timer1" x="100" y="100" width="100px" height="100px" xlink:href="../component/timer/timer1.svg" />  
 <image id="battery1" x="200" y="200" width="100px" height="100px" xlink:href="../component/battery/30x20_ochre.svg" />
 <script xlink:href="pathMaker.js" type="text/javascript" id="pathMaker" />  
</svg>

我尝试使用的脚本如下所示:

newpath = document.createElementNS("SVG","path");  
newpath.setAttribute("id", "pathIdD");  
newpath.setAttribute("d", "M 1,97.857143 C 19.285714,96.428571 24.016862,131.64801 90.714286,132.85714 140.78762,133.7649 202.79376,66.16041 202.79376,66.16041");  
newpath.setAttribute("stroke", "black");  
newpath.setAttribute("stroke-width", 3);  
newpath.setAttribute("opacity", 1);  
newpath.setAttribute("fill", "none");

document.getElementById("fullPageID").appendChild(newpath);

我只想做一些简单的工作。我是否认为我不需要像在Library 中找到的那样复杂的解决方案来使用 Javascript 生成 SVG 路径??

谢谢。

4

3 回答 3

48

有两个问题:

  1. 正如已经指出的,您必须使用完整的命名空间 uri,所以在这种情况下:

    newpath = document.createElementNS('http://www.w3.org/2000/svg',"path");  
    
  2. 还需要考虑命名空间来设置属性。好消息是您可以null作为命名空间 uri 传入,因此:

    newpath.setAttributeNS(null, "d", "M 1,97.857143 C 19.285714,96.428571 24.016862,131.64801 90.714286,132.85714 140.78762,133.7649 202.79376,66.16041 202.79376,66.16041");
    

此外,这里有两种方法可以更轻松地处理 svg 命名空间(假设它是一个独立的 svg,而不是嵌入在 HTML 中):

  • 要引用 svg 元素,您可以使用document.rootElement.
  • document.rootElement.getAttribute(null, "xmlns")返回一个空字符串(虽然使用此方法请求其他属性确实有效。相反,使用document.rootElement.namespaceURI.

因此,在您的代码中,您可以进行以下重写:

从:

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

至:

 newpath = document.createElementNS(document.rootElement.namespaceURI,"path");  

要附加元素,您可以从:

document.getElementById("fullPageID").appendChild(newpath);

至:

document.rootElement.appendChild(newpath);

所以最终的脚本是:

newpath = document.createElementNS(document.rootElement.namespaceURI,"path");  
newpath.setAttributeNS(null, "id", "pathIdD");  
newpath.setAttributeNS(null, "d", "M 1,97.857143 C 19.285714,96.428571 24.016862,131.64801 90.714286,132.85714 140.78762,133.7649 202.79376,66.16041 202.79376,66.16041");  
newpath.setAttributeNS(null, "stroke", "black"); 
newpath.setAttributeNS(null, "stroke-width", 3);  
newpath.setAttributeNS(null, "opacity", 1);  
newpath.setAttributeNS(null, "fill", "none");

document.rootElement.appendChild(newpath);
于 2012-05-11T06:46:47.663 回答
4

命名空间需要是“http://www.w3.org/2000/svg”,而不是createElementNS调用中的“SVG”。

于 2012-05-11T06:13:30.133 回答
0

你可以得到一个免费的命名空间并且偷偷地通过放置一个路径元素,使用一个 id 来隐藏它,然后克隆它。这是一个使用 jQuery 的示例:

HTML

<svg ...>
  <path id="pathFactory"></path>
</svg>

CSS

#pathFactory {
  display: none;
}

Javascript

var path = $('#pathFactory').clone().removeAttr('id');

您的路径变量现在是一个完整的工作路径,具有适当的命名空间,未隐藏并准备附加到 svg。

于 2021-04-27T01:07:34.113 回答