Javascript 如何向svg元素添加圆

Javascript 如何向svg元素添加圆,javascript,jquery,html,dom,svg,Javascript,Jquery,Html,Dom,Svg,我试图在svg中动态地放置圆圈。在index.html文件中,我创建了这个svg部分 <svg id="svgArea" width="500" height="500"></svg> 我试图实现的是在单击按钮时动态创建n个圆。然后在另一个按钮上逐个单击删除按钮。我已经找到了一个解决方案,下面是该方法的一个最小示例。但为了更灵活,我建议使用图书馆。查看演示(您必须向下滚动才能看到按钮) HTML <svg id="svgArea" width="500" hei

我试图在svg中动态地放置圆圈。在
index.html
文件中,我创建了这个
svg
部分

<svg id="svgArea" width="500" height="500"></svg> 

我试图实现的是在单击按钮时动态创建n个圆。然后在另一个按钮上逐个单击删除按钮。

我已经找到了一个解决方案,下面是该方法的一个最小示例。但为了更灵活,我建议使用图书馆。查看演示(您必须向下滚动才能看到按钮)

HTML

<svg id="svgArea" width="500" height="500"></svg>
<button id="addCircle">Add a circle</button>

加一个圆圈
JS

var x = 50;
var y = 50;
var xMax = $('#svgArea').width();
var yMax = $('#svgArea').height();

$("#addCircle").click(function () {
    var existingContent = $('#svgArea').html();
    var toInsert = '<circle cx="' + x + '" cy="' + y + '" r="40" stroke="green" stroke-width="4" fill="yellow" />';
    $('#svgArea').html(existingContent + toInsert);
    if ((x + 100) <= xMax) {
        x += 100;
    } else {
        if ((y + 100) <= yMax) {
            y += 100;
            x = 50;
        } else {
            alert("There is no place inside the canvas!");
        }
    }
});
var x=50;
变量y=50;
var xMax=$('#svgArea').width();
var yMax=$('#svgArea').height();
$(“#添加圆”)。单击(函数(){
var existingContent=$('#svgArea').html();
var-toInsert='';
$('#svgArea').html(现有内容+toInsert);

如果((x+100)变量x和y的可能重复项以及边界碰撞检查不需要,这里只是噪声。
<svg id="svgArea" width="500" height="500"></svg>
<button id="addCircle">Add a circle</button>
var x = 50;
var y = 50;
var xMax = $('#svgArea').width();
var yMax = $('#svgArea').height();

$("#addCircle").click(function () {
    var existingContent = $('#svgArea').html();
    var toInsert = '<circle cx="' + x + '" cy="' + y + '" r="40" stroke="green" stroke-width="4" fill="yellow" />';
    $('#svgArea').html(existingContent + toInsert);
    if ((x + 100) <= xMax) {
        x += 100;
    } else {
        if ((y + 100) <= yMax) {
            y += 100;
            x = 50;
        } else {
            alert("There is no place inside the canvas!");
        }
    }
});