anjo
anjo

Reputation: 345

How to add a circle to svg element

I'm trying to put circles in svg dynamically. In index.html file I created this svg section.

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

In js file i tried this

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

This seems not working.

Tried the below code, but couldn't find how to apply cx, cy, r ...

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

What I am trying to achieve is dynamically create n circles on a button click. And on another button click delete buttons one by one.

Upvotes: 2

Views: 5236

Answers (1)

Ramiz Wachtler
Ramiz Wachtler

Reputation: 5683

I've managed to get a solution, here is a minimal example of the approach. But for more flexibility, I would suggest to use a library. Take a look at the fiddle for a demo (You've to scroll down to see the button).

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

Upvotes: 1

Related Questions