2

I'm trying to create a new <img> with the <svg> tag with JavaScript every time I click on the button. When I see the result in the console firebug it works correctly, but nothing on screen displays. What I want is for an image <svg> to appear after the last one every time you click the button.

Thanks in advance.

    var svgNS = "http://www.w3.org/2000/svg"; 

mybtn.addEventListener("click", createCircleSVG);


    function createCircleSVG(){
      var d = document.createElement('svg');
      d.setAttribute('id','mySVG');

      document.getElementById("svgContainer").appendChild(d); 
      createCircle();
    }    

function createCircle(){

        var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle."
        myCircle.setAttributeNS(null,"id","mycircle" + opCounter++);
        myCircle.setAttributeNS(null,"cx",25);
        myCircle.setAttributeNS(null,"cy",25);
        myCircle.setAttributeNS(null,"r",100);
        myCircle.setAttributeNS(null,"fill","black");
        myCircle.setAttributeNS(null,"stroke","blue");

        document.getElementById("mySVG").appendChild(myCircle);
    }  
BSMP
  • 4,596
  • 8
  • 33
  • 44
julio
  • 23
  • 6
  • Similar question with same answer: [SVG not showing up when added to HTML](http://stackoverflow.com/questions/13691424/svg-not-showing-up-when-added-to-html) "Your svg is being inserted but out of your viewport so you can't see it, add some width and height to the svg..." – Yogi May 30 '15 at 19:19

2 Answers2

0

You need to create the svg element in the SVG namespace using createElementNS (like you already do for the circle) e.g.

var d = document.createElementNS(svgNS, 'svg');

giving the SVG element a width and height is also necessary

    d.setAttribute("width", "100%");
    d.setAttribute("height", "100%");

Note here we can use setAttribute as the attributes are in the null namespace. You can convert the circle setAttributeNS calls too if you want.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
0

Create a SVG:

var svg = document.createElementNS(ns, 'svg');

First function:

function createSVG() { ... }

Second function:

function createSVGCircle() { createSVG() ... }

Or separated:

createSVG();
createSVGCircle();

Example