我想生成随机尺寸的随机矩形而不会发生碰撞。在这一刻,我有这个,但它与碰撞,我已经失去了我的解决方案的想法。
<html>
<head>
</head>
<body>
<svg id="svgOne" xmlns="http://www.w3.org/2000/svg" width="550" height="550">
</svg>
<script type="text/javascript">
var svgns = "http://www.w3.org/2000/svg";
function rectan()
{
for (var i = 0; i < 5; i++) {
var x = Math.floor(Math.random() * 200) + 1 ;
y = Math.floor(Math.random() * 200) + 1 ;
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', 'none');
rect.setAttributeNS(null, 'stroke', '#010101');
document.getElementById('svgOne').appendChild(rect);
}
}
rectan();
</script>
</body>
</html>
有几种方法可以做到这一点。
可选附加功能:
x * maxRectSize, y * maxRectSize
使用选项1,它将更加密集,但您将获得更精细的结果,特别是如果您执行可选的附加功能。
使用选项2,您将获得一个矩形网格,它们不会在随机位置,但它会快速运行。
另一种方法是使用选项2生成起始画布,然后您可以在其上应用选项1以填补空白。