2013-10-09 28 views
6

我一直在尝试在HTML中使用javascript来处理svg操作的hello世界。我编写了下面的代码,虽然它生成了正确的html,但在浏览器中没有看到任何输出,也没有看到任何错误。svg圈没有用javascript绘制

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

我哪里错了?提前致谢。

回答

21

需要使用SVG XML名称空间创建SVG元素。你可以做,使用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> 
+0

感谢zneak,就像一个魅力现在。我现在可以睡了。 –

+4

当然可以。如果它解决了您的问题,请不要忘记单击答案左侧的复选标记。 – zneak