admin管理员组文章数量:1242888
I want to draw a square by using path in SVG created with JS. But the browsers do not accept this:
Javascript:
var svg = document.createElement('svg');
svg.width = "200";
svg.height = "200";
document.body.appendChild(svg);
var path = document.createElement('path');
path.setAttribute('d','M100,0 L200,100 100,200 0,100Z');
path.setAttribute('fill','red');
svg.appendChild(path);
HTML (output):
<svg width="200" height="200">
<path d="M100,0 L200,100 100,200 0,100Z" fill="red"/>
</svg>
I want to draw a square by using path in SVG created with JS. But the browsers do not accept this:
Javascript:
var svg = document.createElement('svg');
svg.width = "200";
svg.height = "200";
document.body.appendChild(svg);
var path = document.createElement('path');
path.setAttribute('d','M100,0 L200,100 100,200 0,100Z');
path.setAttribute('fill','red');
svg.appendChild(path);
HTML (output):
<svg width="200" height="200">
<path d="M100,0 L200,100 100,200 0,100Z" fill="red"/>
</svg>
Share
Improve this question
edited Jan 4, 2016 at 13:14
Kardaw
asked Jan 4, 2016 at 13:04
KardawKardaw
4013 silver badges15 bronze badges
2 Answers
Reset to default 16createElement can only be used to create html elements. To create SVG elements you must use createElementNS and supply the SVG namespace as the first argument.
Also document.body.appendChild('svg'); is presumably a typo as you want to add the svg element and not a string containing the text 'svg'
var svg = document.createElementNS('http://www.w3/2000/svg', 'svg');
svg.setAttribute('width','200');
svg.setAttribute('height','200');
document.body.appendChild(svg);
var path = document.createElementNS('http://www.w3/2000/svg', 'path');
path.setAttribute('d','M100,0 L200,100 100,200 0,100Z');
path.setAttribute('fill','red');
svg.appendChild(path);
Use createElementNS
instead of createElement
.
本文标签: Dynamically add a full svg shape (with pure Javascript)Stack Overflow
版权声明:本文标题:Dynamically add a full svg shape (with pure Javascript) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740164246a2234998.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论