Dynamically created SVG elements are not rendered

2019-05-23 01:06发布

I am trying to use SVG markup in my HTML in order to render some graphics. The problem was very tricky because I just realized that the issue is when generating the SVG programmatically.

The markup

What I want to end up in my page is this fragment of code:

<svg>
  <circle cx="20" cy="20" r="15"></circle>
</svg>

If you take this and paste it inside a page, all is fine and the a black circle is rendered!

Creating the SVG dynamically

But I want to create this content using Javascript, so I have this:

var container = document.createElement("div");
var svg = document.createElement("svg");

var circle = document.createElement("circle");
circle.setAttribute("cx", "20");
circle.setAttribute("cy", "20");
circle.setAttribute("r", "15");

svg.appendChild(circle);
container.appendChild(svg);
document.body.appendChild(container);

Well, try to execute this in fiddle or in your browser and you'll see it will not be rendered. When you inspect the HTML, you see that the circle is not taking any space.

What is the problem?

1条回答
不美不萌又怎样
2楼-- · 2019-05-23 01:20

you have to use "document.createElementNS("http://www.w3.org/2000/svg", "svg");" to create svg elements

var container = document.createElement("div");
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "20");
circle.setAttribute("cy", "20");
circle.setAttribute("r", "15");

svg.appendChild(circle);
container.appendChild(svg);
document.body.appendChild(container);

查看更多
登录 后发表回答