Element created with createElementNS doesn't show

青春壹個敷衍的年華 提交于 2021-02-17 03:22:15

问题


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

回答1:


Create a SVG:

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

First function:

function createSVG() { ... }

Second function:

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

Or separated:

createSVG();
createSVGCircle();

Example




回答2:


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.



来源:https://stackoverflow.com/questions/30549139/element-created-with-createelementns-doesnt-show

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!