最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Dynamically add a full svg shape (with pure Javascript) - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 16

createElement 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.

发布评论

评论列表(0)

  1. 暂无评论