2

親のサイズを合計するランダムなサイズの子 div で親 div を埋める jQuery/javascript を使用した関数を作成したいと思います。

たとえば、コンテナ div を 1200px x 600px の比率で埋める 10 個の子 div

<div class="container">
   <!-- 10 child divs with random height and width. -->
</div>
4

2 に答える 2

7

長方形を 2 つのサブ長方形に分割する関数を使用して、これらを再帰的に分割できます。

  • 長方形を 2 つの部分に分割するときに、偶数 N 個の部分長方形を含む必要がある場合、各部分には N/2 個の部分長方形が含まれます。
  • 四角形を 2 つに分割するときに、奇数個の葉のサブ四角形を含める必要がある場合、大きな部分にはもう一方よりも 1 つの子が多くなります。

function fillWithChilds(el, N) {
  function rand(n) {
    /* weight=100 means no random
       weight=0 means totally random  */
    var weight = 50;
    return Math.floor(weight*n/2+n*(100-weight)*Math.random())/100;
  }
  function main(N, x, y, hei, wid) {
    if(N < 1) return;
    if(N === 1) {
      var child = document.createElement('div');
      child.className = 'child';
      child.style.left = x + 'px';
      child.style.top = y + 'px';
      child.style.width = wid + 'px';
      child.style.height = hei + 'px';
      el.appendChild(child);
      return;
    }
    var halfN = Math.floor(N/2);
    if(wid > hei) {
      var newWid = rand(wid);
      if(2*newWid > wid) halfN = N-halfN;
      main(halfN, x, y, hei, newWid);
      main(N-halfN, x+newWid, y, hei, wid-newWid);
    } else {
      var newHei = rand(hei);
      if(2*newHei > hei) halfN = N-halfN;
      main(halfN, x, y, newHei, wid);
      main(N-halfN, x, y+newHei, hei-newHei, wid);
    }
  }
  main(N, 0, 0, el.clientHeight, el.clientWidth);
}
fillWithChilds(document.getElementById('wrapper'), 11);
#wrapper {
  background: #ccf;
  position: relative;
  height: 300px;
  width: 400px
}
.child {
  background: #cfc;
  outline: 2px solid red;
  position: absolute;
}
<div id="wrapper"></div>

于 2013-07-12T02:19:46.737 に答える