[英]Create SVG element via javascript
I need to create this structure using only javascript: 我只需要使用javascript创建这个结构:
<svg>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#circle"></use>
</svg>
But I have trouble with creating xmlns:xlink
attribute. 但是我在创建
xmlns:xlink
属性时遇到了麻烦。 Here is my js code: 这是我的js代码:
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
// throws error here
use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#circle');
svg.appendChild(use);
If I comment string with settings xmlns:xlink
all working good and makes svg same as above, but without xmlns:xlink
. 如果我用设置
xmlns:xlink
注释字符串一切正常,并使svg与上面相同,但没有xmlns:xlink
。
I seen a lot of question similar to mine, but they didn't solve my problem. 我看到很多类似于我的问题,但他们没有解决我的问题。
Regarding 关于
use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');
You don't need that line and actually it's not valid. 你不需要那条线,实际上它是无效的。
The xmlns:xlink attribute set automatically when you create an element with createElementNS or an attribute with setAttributeNS if you're creating an element/attribute in an XML document and it's not required if you're creating an element in a html document. 如果您在XML文档中创建元素/属性,则在使用createElementNS创建元素时会自动设置xmlns:xlink属性;如果您在html文档中创建元素,则不需要xmlns:xlink属性。
Here we go: 开始了:
// "circle" may be any tag name
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
// Set any attributes as desired
shape.setAttribute("cx", 25);
shape.setAttribute("cy", 25);
shape.setAttribute("r", 20);
shape.setAttribute("fill", "green");
// Add to a parent node; document.documentElement should be the root svg element.
// Acquiring a parent element with document.getElementById() would be safest.
document.documentElement.appendChild(shape);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.