20

SVGで100個の長方形を描く方法を知りたいのですが。

このコードで1つの長方形を作成しました:

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

同じサイズで位置が異なる100個の長方形を描画したいと思います(10行と10行など)。それを速くする方法は?いくつかのループ?

4

1 に答える 1

37

次のループで画面を埋めることができます。

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>

ランダムに配置された100個の正方形が必要な場合は、次のように実行できます。

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

2番目のjsfiddle

于 2012-10-08T17:52:31.927 に答える