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

本文标签: Dynamically add a full svg shape (with pure Javascript)Stack Overflow