Javascript 在SVG中动态绘制矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12786797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw rectangles dynamically in SVG
提问by Jacek Krasucki
I would like to know how to draw 100 rectangles with SVG.
我想知道如何用 SVG 绘制 100 个矩形。
I made one rectangle with this code:
我用以下代码制作了一个矩形:
<!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>
I woukd like to draw 100 of rectangles with same size, different position (like 10 in row and 10 rows). How to do it fast? Some loop?
我想绘制 100 个具有相同大小、不同位置的矩形(如 10 行和 10 行)。怎么做快?一些循环?
回答by saml
You can fill the screen with the following loop:
您可以使用以下循环填充屏幕:
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);
}
}
If you just want 100 randomly placed squares, you could do:
如果你只想要 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);
}