2012-10-08 41 views
14

Me gustaría saber cómo dibujar 100 rectángulos con SVG.Dibujar rectángulos dinámicamente en SVG

Hice un rectángulo con este código:

<!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> 

I woukd gusta dibujar 100 de rectángulos con el mismo tamaño, posición diferente (como 10 en la fila y 10 filas). ¿Cómo hacerlo rápido? ¿Algún bucle?

+0

utiliza una una biblioteca opción, o ¿quieres hacer esto con JavaScript directo? – nrabinowitz

+1

Usar una biblioteca para esto sería una exageración completa – saml

Respuesta

23

Usted puede llenar la pantalla con el siguiente bucle:

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

Si lo que desea es 100 cuadrados colocados aleatoriamente, se puede hacer:

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

Es estúpido pero, ¿podría mostrarme cómo debería verse todo el código? –

+0

Lo hice, THX por ayuda. –

+0

¿Podría aceptar, si esto responde su pregunta? – saml

Cuestiones relacionadas