Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw rectangles dynamically in SVG

Tags:

I would like to know how to draw 100 rectangles with SVG.

I made one rectangle with this code:

<!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 like to draw 100 of rectangles with same size, different position (like 10 in row and 10 rows). How to do it fast? Some loop?

like image 343
Jacek Krasucki Avatar asked Oct 08 '12 17:10

Jacek Krasucki


People also ask

Which element is used to create a SVG rectangle?

The <rect> element is a basic SVG shape that draws rectangles, defined by their position, width, and height.

How do I put text in a SVG rectangle?

<svg> with <rect> and <text> elements inside it used to write text inside the rectangle of SVG. To do that, we need to join the<rect> and <text> elements. Refer the topics Draw Rectangle and Draw Text to get the clear understanding of SVG <rect> and <text> elements.

How do I display a rectangle box in HTML?

The width and height attributes of the <rect> element define the height and the width of the rectangle. The style attribute is used to define CSS properties for the rectangle. The CSS fill property defines the fill color of the rectangle. The CSS stroke-width property defines the width of the border of the rectangle.


1 Answers

You can fill the screen with the following loop:

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,'width','50' );
    rect.setAttributeNS( null,'height','50' );
    rect.setAttributeNS( null,'fill','#'+Math.round( 0xffffff * Math.random()).toString(16) );
    document.getElementById( 'svgOne' ).appendChild( rect );
  }
}
body{overflow:hidden; margin:0; }
svg{width:100vw; height:100vh;}
<svg id='svgOne'></svg>

If you just want 100 randomly placed squares, you could do:

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, 'width', '50');
  rect.setAttributeNS(null, 'height', '50');
  rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16));
  document.getElementById('svgOne').appendChild(rect);
}

jsfiddle for the second one

like image 158
saml Avatar answered Sep 18 '22 21:09

saml