【问题标题】:Generating an SVG shape生成 SVG 形状
【发布时间】:2015-01-26 17:16:38
【问题描述】:

我正在努力使用 Firebug“动态”创建 SVG 元素。这是一个同样失败的 jsfiddle 示例。

http://jsfiddle.net/CLEZc/3/

<svg width="500" height="500">
     <circle id="c1" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
  </svg>
<div id="genR" onclick="genRect();" >Generate</div>  




function genRect () {
    var rect = document.createElementNS ("http://www.w3.org/2000/svg", "rect");
    var svg = document.getElementsByTagName ("svg")[0];
    console.log (rect);
    console.log (svg);
    rect.setAttribute ("width", "50");
    rect.setAttribute ("height", "50");
    rect.setAttribute ("fill", "#e11a51");
    rect.setAttribute ("stroke", "blue");
    rect.setAttribute ("x", "75");
    rect.setAttribute ("y", "150");
    svg.appendChild (rect);
}

谢谢,

【问题讨论】:

    标签: javascript svg namespaces jsfiddle createelement


    【解决方案1】:

    找到原因。

    使用这个 HTML:

    <svg id="svnContainer" width="500" height="500">
        <circle id="c1" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
    </svg>
    <div id="genR" onclick="genRect();" >Generate</div>  
    

    使用这个 Javascript:

    window.genRect = function() {
        var rect = document.createElementNS ("http://www.w3.org/2000/svg", "rect");
        var svg = document.getElementById('svnContainer');
        console.log (rect);
        console.log (svg);
        rect.setAttribute ("width", "50");
        rect.setAttribute ("height", "50");
        rect.setAttribute ("fill", "#e11a51");
        rect.setAttribute ("stroke", "blue");
        rect.setAttribute ("x", "75");
        rect.setAttribute ("y", "150");
        svg.appendChild (rect);
    }
    

    我在 HTML 中所做的更改可能没有必要,但更安全,因为通过使用 ID(应该是唯一的),您可以保证页面中没有其他元素具有相同的内容(而如果您使用名字,你不能确定)。

    第二个更改(使其在 jsfiddle 上运行的重要更改)是您定义函数的方式。您需要按照这篇文章的说明将其设为全局(原因是 jsfiddle 运行您的代码的方式):JavaScript not running on jsfiddle.net

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      相关资源
      最近更新 更多