使用JavaScript时未绘制SVG圆形

10

我一直在尝试使用JavaScript在HTML中进行SVG操作的“Hello World”。我编写了下面的代码,虽然它生成了正确的HTML,但是在浏览器中没有看到任何输出,也没有看到任何错误。

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElement("svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElement("circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>

我哪里做错了?谢谢提前。

1个回答

33

SVG元素需要使用SVG XML命名空间创建。您可以使用createElementNS并使用http://www.w3.org/2000/svg命名空间来完成:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>

4
好的。如果我的回答解决了你的问题,请不要忘记在答案左侧点击勾选标记。 - zneak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接