2012-10-08 75 views
14

我想知道如何用SVG绘制100个矩形。在SVG中动态绘制矩形

我制成一个矩形,此代码:

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

我woukd提请用相同的大小,不同的位置(在排样10和10行)的矩形100。如何快速做到这一点?一些循环?

+0

使用图书馆的选项,还是你想用直接的JavaScript来做到这一点? – nrabinowitz

+1

使用这个库是完全过度的 – saml

回答

23

你可以用下面的循环填充屏幕:

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

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

jsfiddle for the second one

+0

它很笨,但是,你能告诉我整个代码应该看起来怎么样? –

+0

我做到了,THX求救。 –

+0

你能接受,如果这回答你的问题? – saml