Generating an SVG shape

109 views Asked by At

Im struggling to 'dynamically' create SVG elements using Firebug. Here is a jsfiddle example which also fails.

http://jsfiddle.net/CLEZc/3/

<svg width="500" height="500">
     <circle id="c1" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
  </svg>
<div id="genR" onclick="genRect();" >Generate</div>  




function genRect () {
    var rect = document.createElementNS ("http://www.w3.org/2000/svg", "rect");
    var svg = document.getElementsByTagName ("svg")[0];
    console.log (rect);
    console.log (svg);
    rect.setAttribute ("width", "50");
    rect.setAttribute ("height", "50");
    rect.setAttribute ("fill", "#e11a51");
    rect.setAttribute ("stroke", "blue");
    rect.setAttribute ("x", "75");
    rect.setAttribute ("y", "150");
    svg.appendChild (rect);
}

Thanks,

1

There are 1 answers

0
Rodrigo Quesada On BEST ANSWER

Found the cause.

Use this HTML:

<svg id="svnContainer" width="500" height="500">
    <circle id="c1" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<div id="genR" onclick="genRect();" >Generate</div>  

Use this Javascript:

window.genRect = function() {
    var rect = document.createElementNS ("http://www.w3.org/2000/svg", "rect");
    var svg = document.getElementById('svnContainer');
    console.log (rect);
    console.log (svg);
    rect.setAttribute ("width", "50");
    rect.setAttribute ("height", "50");
    rect.setAttribute ("fill", "#e11a51");
    rect.setAttribute ("stroke", "blue");
    rect.setAttribute ("x", "75");
    rect.setAttribute ("y", "150");
    svg.appendChild (rect);
}

The change I made in the HTML might no be necessary, but is safer, because by using an ID (which should be unique) you guarantee that there is no other element in the page with the same (whereas if you use the name, you cannot be certain).

The second change (the important one in order to make it work on jsfiddle), is the way in which you defined the function. You need to make it global as explained on this post (the reason being because of the way jsfiddle runs your code): JavaScript not running on jsfiddle.net