在SVG中动态绘制矩形

20

我想知道如何使用SVG绘制100个矩形。

我用以下代码绘制了一个矩形:

<!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列)。应该如何快速完成?需要使用循环吗?


使用库是一个选项,还是你想使用纯JavaScript完成这个任务? - nrabinowitz
1
使用库来完成这个任务会完全杀鸡焉用牛刀。 - saml
1个回答

38

您可以使用以下循环将屏幕填满:

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

第二个的JSFiddle链接


很蠢,但你能给我展示一下整个代码应该是什么样子吗? - Jacek Krasucki
我还有一个问题?如果我只想要100个正方形 - 每行10个正方形,共10行怎么办? - Jacek Krasucki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接