How to dynamically create an element in SVG?

2

I want to use a number of one variable and create several SVG objects the same. Just change your position and name in JavaScript.

As in the for loop sampled 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" />
}
    
asked by anonymous 14.11.2014 / 16:17

1 answer

4

Here's a suggestion based on this question .

In the background I create the new element inside a function, so the for loop gets 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>
    
14.11.2014 / 16:31