Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 不使随机放置的对象重叠的算法?_Javascript_Html_Algorithm - Fatal编程技术网

Javascript 不使随机放置的对象重叠的算法?

Javascript 不使随机放置的对象重叠的算法?,javascript,html,algorithm,Javascript,Html,Algorithm,假设我有一个div,我插入了其他具有随机生成的位置值的div(上,左) 我想要一个不让元素重叠的算法。我可以将位置设置为相对,但元素会溢出容器 for(变量i=0;i

假设我有一个div,我插入了其他具有随机生成的位置值的div(上,左)

我想要一个不让元素重叠的算法。我可以将位置设置为相对,但元素会溢出容器

for(变量i=0;i<20;i++)
{
var elem=$(document.createElement('div');
元素属性('class','child')。
css
({
“顶部”:Math.floor(Math.random()*((高度-50)-30+1)+30),
“左”:Math.floor(Math.random()*((宽度-50)-30+1)+30),
“宽度”:30,
身高:30
});
$('包装器').append(elem);
}

如果相对于总面积没有放置太多对象,则只需检测交点,并在获得交点时重新采样即可。顺便说一句,如果您想从区域中指定k个非重叠对象的方法中获得一个均匀的随机样本,那么选择第一个对象全局均匀随机,然后保持其固定不是正确的方法,因为为了避免重叠,对象位置可能会有偏差。最好在初始的非重叠指定中,将对象彼此均匀地隔开,然后继续选择一个对象并稍微晃动其位置,在与另一个对象碰撞时改变方向。如果你这样做的次数足够多,你将从你真正想要的样本中获得一个随机样本

for (var i = 0 ; i < 20 ; i++)
{
    var elem = $(document.createElement('div'));
    elem.attr('class', 'child').
    css
    ({
        'top': Math.floor(Math.random()*((height-50)-30+1)+30),
        'left': Math.floor(Math.random()*((width-50)-30+1)+30),
        'width' : 30,
        'height': 30
    });
    $('#wrapper').append(elem);
}