【问题标题】:How to add a circle to svg element如何在 svg 元素中添加一个圆圈
【发布时间】:2016-02-21 06:44:09
【问题描述】:

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

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

js 文件中我尝试了这个

$('#svgArea').append('<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />');

这似乎不起作用。

试过下面的代码,但找不到如何应用 cx, cy, r ...

var crcl= document.createElement("CIRCLE");
$('#svgArea').append(crcl);

我想要实现的是在单击按钮时动态创建 n 个圆圈。然后在另一个按钮上一个一个地点击删除按钮。

【问题讨论】:

标签: javascript jquery html dom svg


【解决方案1】:

我设法找到了解决方案,这是该方法的一个最小示例。但为了获得更大的灵活性,我建议使用库。查看 fiddle 的演示(您必须向下滚动才能看到按钮)。

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

【讨论】:

  • 不要求变量 x 和 y 以及边界碰撞检查,在这里只是噪音。
猜你喜欢
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
相关资源
最近更新 更多