我是 svg 的新手。我想做的是用 JS 创建一个椭圆元素并将其附加到 SVG 标签。 HTML代码是
<svg width="640" height="480">
<ellipse cx="200" cy="100" rx="90" ry="60" stroke-width="10" stroke="orange" fill="none" opacity="0.6"/>
<ellipse cx="200" cy="100" rx="70" ry="40" stroke-width="10" stroke="green" fill="none" opacity="0.6"/>
</svg>
下面是JS代码
<script type="text/javascript">
var el=document.createElement('ellipse');
$(el).attr("cx",300);
$(el).attr("cy",200);
$(el).attr("stroke","red");
$(el).attr("stroke-width","10");
$(el).attr("fill","green");
$(el).attr("rx",120);
$(el).attr("ry",80);
$("svg").append(el);
</script>
但是椭圆没有出现在视口(viewport)上,但是当我检查 HTML 时,我发现我创建的椭圆元素附加到 SVG。以这种方式创建时有什么区别以及将元素动态添加到 SVG 的正确方法是什么
最佳答案
您拥有的是自定义 HTML 元素,而不是 SVG 元素。使用 createElementNS
创建 SVG 元素:
$(function(){
var el = document.createElementNS("http://www.w3.org/2000/svg", 'ellipse');
el.setAttribute('cx', 300);
el.setAttribute('cy', 200);
el.setAttribute('stroke', "red");
el.setAttribute('stroke-width', 10);
el.setAttribute('fill', "green");
el.setAttribute('rx', 120);
el.setAttribute('ry', 80);
$("svg").append(el);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<svg width="640" height="480">
<ellipse cx="200" cy="100" rx="90" ry="60" stroke-width="10" stroke="orange" fill="none" opacity="0.6"/>
<ellipse cx="200" cy="100" rx="70" ry="40" stroke-width="10" stroke="green" fill="none" opacity="0.6"/>
</svg>
关于javascript - "ellipse"通过JS创建的元素没有出现在html中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31762733/