如何动态添加元素到HTML5 SVG?

Jon*_*nas 4 javascript html5 svg createelement

我已经阅读了几个与此类似的问题,但我无法使代码正常工作.我想在用户点击SVG区域时添加SVG元素.

这是我的带有SVG的HTML5,它正确呈现:

<!DOCTYPE html>
<html>
  <head>
    <script src="jquery-1.6.2.min.js"></script>
    <script src="svgdraw.js"></script>
  </head>
  <body>
    <svg id="canvas" width="500" height="500">
    <circle cx="80" cy="80" r="50" fill="blue"/>
    </svg>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

以下是在click事件上执行的JavaScript:

    var svgDocument = document.getElementById('canvas');
    var svgns = "http://www.w3.org/2000/svg";
    var shape = svgDocument.createElementNS(svgns,"circle");
    shape.setAttributeNS(null, "cx", 25);
    shape.setAttributeNS(null, "cy", 25);
    shape.setAttributeNS(null, "r", 20);
    shape.setAttributeNS(null, "fill", "green");
    document.getElementById('canvas').appendChild(shape);
Run Code Online (Sandbox Code Playgroud)

在Google Chrome中,我收到一条createElementNS不存在的错误消息.但如果我删除所有NSnull任何一个,我无法使它工作.这样做的正确方法是什么?不同的浏览器是不同的?

Kil*_*one 6

据我所知,createElementNS()document变量的一部分,请尝试:

var shape = document.createElementNS(svgns,"circle");
Run Code Online (Sandbox Code Playgroud)