我正在努力使用 Firebug“动态”创建 SVG 元素。这是一个 jsfiddle 示例,也失败了。
<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);
}
谢谢
最佳答案
找到原因了。
使用此 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
关于javascript - 生成 SVG 形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27181998/