2

ボックスを固定サイズで埋める必要があります.9つの ランダムなサイズの形状で埋める必要があります.

私は 9 つの形状を持っているので、1 つまたは複数を別の形状の上に重ねることができます。これのポイントは、これらの形状がランダムに散らばっているかのように、ランダム効果を作成することです。しかし、ここでも空白を残すことはできません。これは非常に重要であり、最も難しい部分です。

だから、私がより良くしていることを想像するために、これがどのように見えるべきかの例があります

ここに画像の説明を入力

また、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);
}
4

1 に答える 1

6

実際、答えは非常に難しいものです。ある種のスペース充填アルゴリズムが必要なため、depp を使用できます。

正直なところ、私はこの種のことにそれほど強くはありませんが、あなたがそれを処理できる場合は、次のトピックをお勧めします。

  • フラクタル塗りつぶしアルゴリズム
  • 重心緩和のあるボロノイセル
  • 二分木

代わりに、後者のバイナリ ツリーの簡単な実装を書き留めようとしました。これは、空間の領域をより小さな断片に再帰的に再分割することによって機能します。

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;
}

通話中

binary(struct);

分割された領域の配列を返します。これが出発点になることを願っています(また、画像をボックスにランダムに配置するためだけにメモリを大量に使用するアルゴリズムを実行したくないと思いますが、間違っているかもしれません:))

于 2013-05-13T16:50:39.280 に答える