How to create an element in SVG dynamically?

Asked

Viewed 449 times

2

I want to use a variable number and create multiple identical SVG objects. Just change their position and name in Javascript.

As in the loop for exemplified in the pseudo-code:

for(i=0; i<variavel; i++){
    <circle title=circle cx="250" cy="250" r="5" stroke="black" stroke-width="2" fill="green" />
}

1 answer

4


Here is a suggestion based in this question.

In the background create the new element within a function, so the cycle is cleaner.

var variavel = 10;
var svg = document.querySelector('svg');

for (var i = 0; i < variavel; i++) {
    criarCirculo(i);
}

function criarCirculo(tamanho) {
    var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    shape.setAttributeNS(null, "cx", numeroAleatório(tamanho));
    shape.setAttributeNS(null, "cy", numeroAleatório(tamanho));
    shape.setAttributeNS(null, "r", 20);
    shape.setAttributeNS(null, "fill", "green");
    svg.appendChild(shape);
}

function numeroAleatório(max) {
    return Math.random() * max + Math.random() * max * 100;
}
<svg width="400px" height="400" version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.