svg圈没有用javascript绘制

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)

  • 当然可以.如果它解决了您的问题,请不要忘记单击答案左侧的复选标记. (4认同)