浏览器不呈现动态创建的SVG元素 [英] Dynamically created SVG elements are not rendered by the browser
问题描述
我正在尝试在HTML中使用SVG标记来渲染一些图形。问题非常棘手,因为我刚刚意识到问题是以编程方式生成SVG。
标记
我想在我的页面中最终得到的是这段代码:
< SVG> < circle cx =20cy =20r =15>< / circle>< / svg>
如果你拿这个并将它粘贴在一个页面内,一切都很好,并呈现一个黑色圆圈!
动态创建SVG
但是我想用Javascript创建这个内容,所以我有这个:
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);
好吧,尝试在小提琴或浏览器中执行此操作,您将看到它不会被渲染。当您检查HTML时,您会看到圈
没有占用任何空间。
有什么问题?
你必须使用document.createElementNS(http://www.w3.org / 2000 / svg,svg);
创建svg元素
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);
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?
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);
这篇关于浏览器不呈现动态创建的SVG元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!