美好的一天,
我在创建路径并使用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>
Run Code Online (Sandbox Code Playgroud)
我试图使用的脚本如下:
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);
Run Code Online (Sandbox Code Playgroud)
我只是想做一些简单的工作.我错误地认为我不需要像在Library中使用Javascript生成SVG路径那样复杂的解决方案吗??
谢谢你.
Ant*_*ony 31
有两个问题:
正如已经指出的那样,你必须使用完整的命名空间uri,所以在这种情况下:
newpath = document.createElementNS('http://www.w3.org/2000/svg',"path");
Run Code Online (Sandbox Code Playgroud)还需要在设置名称空间时设置属性.好消息是你可以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");
Run Code Online (Sandbox Code Playgroud)此外,这里有两种方法可以更轻松地处理svg命名空间(假设它是一个独立的svg,而不是嵌入在HTML中):
document.rootElement.document.rootElement.getAttribute(null, "xmlns")返回一个空字符串(虽然请求其他属性确实可以使用此方法.请使用document.rootElement.namespaceURI.因此,在您的代码中,您可以进行以下重写:
从:
newpath = document.createElementNS("http://www.w3.org/2000/svg","path");
Run Code Online (Sandbox Code Playgroud)
至:
newpath = document.createElementNS(document.rootElement.namespaceURI,"path");
Run Code Online (Sandbox Code Playgroud)
要附加元素,您可以从:
document.getElementById("fullPageID").appendChild(newpath);
Run Code Online (Sandbox Code Playgroud)
至:
document.rootElement.appendChild(newpath);
Run Code Online (Sandbox Code Playgroud)
所以最后的脚本将是:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21255 次 |
| 最近记录: |