您可以使用以下循环填充屏幕:
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