Abd*_*der 7 html javascript svg
我一直在尝试使用HTML中的javascript为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>
Run Code Online (Sandbox Code Playgroud)
我哪里错了?提前致谢.
zne*_*eak 23
需要使用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>
Run Code Online (Sandbox Code Playgroud)