Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - Element created with createElementNS doesn't show

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...