Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add an element to HTML5 SVG?

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.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);

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?

like image 652
Jonas Avatar asked Jul 14 '11 18:07

Jonas


1 Answers

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

var shape = document.createElementNS(svgns,"circle");
like image 147
KilZone Avatar answered Nov 01 '22 17:11

KilZone