2012-10-08 10 views
14

Vorrei sapere come disegnare 100 rettangoli con SVG.Disegnare rettangoli dinamicamente in SVG

Feci un rettangolo con questo codice:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<body> 

    <svg id="svgOne" xmlns="http://www.w3.org/2000/svg" width="5000" height="3000"> 
    <rect x="50" y="50" width="50" height="50" fill="black" /> 
    </svg> 

</body> 
</html> 

mi woukd piace disegnare 100 di rettangoli con stessa dimensione, posizione diversa (come 10 in fila e 10 righe). Come si fa in fretta? Un po 'di loop?

+0

sta usando un'una libreria opzione, o vuoi farlo con JavaScript dritto? – nrabinowitz

+1

Utilizzando una libreria per questo sarebbe completo over23. – saml

risposta

23

È possibile riempire lo schermo con il seguente ciclo:

var svgns = "http://www.w3.org/2000/svg"; 
for (var x = 0; x < 5000; x += 50) { 
    for (var y = 0; y < 3000; y += 50) { 
     var rect = document.createElementNS(svgns, 'rect'); 
     rect.setAttributeNS(null, 'x', x); 
     rect.setAttributeNS(null, 'y', y); 
     rect.setAttributeNS(null, 'height', '50'); 
     rect.setAttributeNS(null, 'width', '50'); 
     rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16)); 
     document.getElementById('svgOne').appendChild(rect); 
    } 
} 

Se si desidera solo 100 piazze a disposizione casuale, si potrebbe fare:

for (var i = 0; i < 100; i++) { 
    var x = Math.random() * 5000, 
     y = Math.random() * 3000; 

    var rect = document.createElementNS(svgns, 'rect'); 
    rect.setAttributeNS(null, 'x', x); 
    rect.setAttributeNS(null, 'y', y); 
    rect.setAttributeNS(null, 'height', '50'); 
    rect.setAttributeNS(null, 'width', '50'); 
    rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16)); 
    document.getElementById('svgOne').appendChild(rect); 
} 

jsfiddle for the second one

+0

E 'stupido ma, potresti mostrarmi come dovrebbe apparire l'intero codice? –

+0

L'ho fatto, THX per aiuto. –

+0

Puoi accettare, se questo ha risposto alla tua domanda? – saml

Problemi correlati