Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
    }  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
279 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...