【问题标题】:Element created with createElementNS doesn't show使用 createElementNS 创建的元素不显示
【发布时间】:2015-05-30 17:21:01
【问题描述】:

每次单击按钮时,我都会尝试使用 JavaScript 创建一个带有 <svg> 标记的新 <img>。当我在控制台萤火虫中看到结果时,它可以正常工作,但屏幕上没有任何显示。 我想要的是每次单击按钮时在最后一张图片之后出现一张图片<svg>

提前致谢。

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

【问题讨论】:

  • 具有相同答案的类似问题:SVG not showing up when added to HTML“您的 svg 正在插入,但在您的视口之外,因此您看不到它,请为 svg 添加一些宽度和高度...”跨度>

标签: javascript svg appendchild


【解决方案1】:

创建 SVG:

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

第一个函数:

function createSVG() { ... }

第二个功能:

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

或分开:

createSVG();
createSVGCircle();

Example

【讨论】:

    【解决方案2】:

    您需要使用 createElementNS 在 SVG 命名空间中创建 svg 元素(就像您已经为圆圈所做的那样),例如

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

    给 SVG 元素一个宽度和高度也是必要的

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

    注意这里我们可以使用 setAttribute,因为属性在 null 命名空间中。如果需要,您也可以转换圆形 setAttributeNS 调用。

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 2019-02-22
      • 2019-11-30
      相关资源
      最近更新 更多