admin管理员组

文章数量:1291032

I have read a few questions similar to this, but I can't get my code working properly. I want to add a SVG element when a the user click on the SVG-area.

Here is my HTML5 with SVG, it renders correctly:

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

Here is the JavaScript that is executed on a click event:

    var svgDocument = document.getElementById('canvas');
    var svgns = "";
    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);

In Google Chrome I get an error message that createElementNS doesn't exist. But I can't get it working if I remove all NS and null either. What is the correct way to do this? Is is different for different browsers?

I have read a few questions similar to this, but I can't get my code working properly. I want to add a SVG element when a the user click on the SVG-area.

Here is my HTML5 with SVG, it renders correctly:

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

Here is the JavaScript that is executed on a click event:

    var svgDocument = document.getElementById('canvas');
    var svgns = "http://www.w3/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);

In Google Chrome I get an error message that createElementNS doesn't exist. But I can't get it working if I remove all NS and null either. What is the correct way to do this? Is is different for different browsers?

Share Improve this question asked Jul 14, 2011 at 18:55 JonasJonas 129k102 gold badges327 silver badges405 bronze badges 2
  • When I tried to replicate your problem I encountered that svgDocument was undefined. Any idea why thats happening? – Sayan Commented Oct 30, 2012 at 9:02
  • I though html5 didn't required namespace anymore ?! – yota Commented Aug 21, 2017 at 16:30
Add a ment  | 

1 Answer 1

Reset to default 9

As far as I know createElementNS() is part of the document-variable, try:

var shape = document.createElementNS(svgns,"circle");

本文标签: javascriptHow to dynamically add an element to HTML5 SVGStack Overflow