填充随机大小形状的盒子

Lin*_*nas 2 javascript positioning

我需要填充一个固定大小的盒子,它应该填充9个 随机大小的形状.

由于我有9个形状,一个或多个可以在另一个上面,这就是创建随机效果,好像这些形状是随机散布的.但是再一次不会有任何空白空间,这是非常重要和最困难的部分.

所以想象一下我的表现我做得更好,并举例说明这应该是什么样的

在此输入图像描述

我也设置了jsFiddle,你在这里查看

我在这方面工作了好几个小时,无论我想到什么都没用,所以这只是我正在用代码做的一个非常基本的例子.

我不是要求一个完全正常工作的代码,但任何关于如何从这一点继续的建议都会有所帮助.

由于SO规则要求jsFiddle代码,这里是:

$shape = $('<div class="shape"></div>');
$container = $(".container");

//random shape sizes
shapes = [
    [rand(50, 70), rand(50, 70)],
    [rand(50, 70), rand(50, 70)],
    [rand(60, 70), rand(60, 70)],
    [rand(60, 100), rand(60, 100)],
    [rand(100, 140), rand(100, 140)],
    [rand(100, 140), rand(100, 140)],
    [rand(100, 140), rand(100, 140)],
    [rand(140, 190), rand(140, 190)],
    [rand(150, 210), rand(150, 210)]
];

used = [];
left = 0;
top = 0;

for(i = 1; i <= 3; i++){
    offset = rand(0, 8);

    width = shapes[offset][0];
    height = shapes[offset][1];

    $container.append(
        $shape.css({
            width: width,
            height: height,
            top: top,
            left: left,
            zIndex: i
        })
        .text(i)
        .clone()
    );

    //increase top offset
    top += shapes[offset][1];
}


function rand(from, to){
    return Math.floor((Math.random()*to)+from);
}
Run Code Online (Sandbox Code Playgroud)

six*_*ers 6

实际上答案是一个非常困难的答案,因为你需要某种空间填充算法,我们可以去研究它.

老实说,我并没有那么强大,但我建议 - 如果你能处理它 - 进入这个主题:

  • 分形填充算法
  • Voronoi细胞具有质心松弛
  • 二叉树

我试着写下后者的简单实现,二叉树.它的工作原理是将空间区域递归细分为较小的部分.

var square = {x: 0, y: 0, width: 200, height: 200};
var struct = [square];

function binary(struct) {
    var axis = 1;
    function subdivide(index) {
        var item = struct.splice(index, 1)[0];
        if(axis > 0) {
            var aw = item.width / 2;
            var ow = Math.random() * aw;
            ow -= ow / 2;
            var ax = Math.round(item.width / 2 + ow);
            var bx = item.width - ax;
            struct.push({x: item.x, y: item.y, width: ax, height: item.height});
            struct.push({x: item.x + ax, y: item.y, width: bx, height: item.height});
        } else {
            var ah = item.height / 2;
            var oh = Math.random() * ah;
            oh -= oh / 2;
            var ay = Math.round(item.height / 2 + oh);
            var by = item.height - ay;
            struct.push({x: item.x, y: item.y, width: item.width, height: ay});
            struct.push({x: item.x, y: item.y + ay, width: item.width, height: by});
        }

        axis = -axis;
    }

    while(struct.length < 9) {
        var index = Math.round(Math.random() * (struct.length-1));
        subdivide(index);
    }

    return struct;
}
Run Code Online (Sandbox Code Playgroud)

调用

binary(struct);
Run Code Online (Sandbox Code Playgroud)

返回一组细分区域.希望这可以作为一个起点(我也假设你不想运行一个内存繁重的算法,只是将图像随机放在一个盒子里,但我可能错了:))