【问题标题】:Draw rectangles dynamically in SVG在 SVG 中动态绘制矩形
【发布时间】:2012-09-29 00:04:33
【问题描述】:

我想知道如何用 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 吗?
  • 为此使用库完全是矫枉过正

标签: javascript html svg


【解决方案1】:

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

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;}
&lt;svg id='svgOne'&gt;&lt;/svg&gt;

如果你只想要 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 for the second one

【讨论】:

  • 这很愚蠢但是,你能告诉我整个代码应该是什么样子吗??
  • 我还有一个q?如果我只想要 100 个方格 - 10 行中的 10 个方格怎么办??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 2015-11-24
  • 2013-03-13
  • 2019-08-02
  • 2014-01-13
  • 2011-07-23
相关资源
最近更新 更多