2

私は画像が荒い扱いに耐えるギャラリーを持っています: それらはコンテナ内でランダムにサイズ変更され、配置されます。また、それらは丸みを帯びており、マウスクリックでサイズが変更されます..安心してください。実際には、思ったよりもはるかに簡単です。

さて、これが私の言いたいことの(かわいい)例です:http://dl.dropbox.com/u/5550635/Test%20rounded%20gallery/example2.htm

私の問題は、この例ではかなり明白です。ほとんどの場合、画像が重なっています。
画像の1つをクリックすると、他の画像が下がり、重なり合うことなく線を形成する必要があります。それらの間には少なくとも5ピクセルのマージンがあります.

サンプルページでコメント付きのコードを確認できます。

CSS は非常に単純です。

.project { //class given to the div containing the images
border-radius: 100px;
width: 200px;
height: 200px;
overflow: hidden;
}

#space { //container
width: 550px;
height: 700px;
background: #ccc;
border: 2px solid blue;
}

.parent_project { //parent of the .project div, position absolutely (to fix a problem between position and border-radius)
position: absolute;
}

画像の重複を防ぐための Javascript ソリューションを Web で探しましたが、自分の特性に合ったものを見つけることができませんでした。私の問題を見て、あなたの科学の一部を共有していただければ、とても感謝しています. ありがとう!

4

1 に答える 1

1

円の中点と半径を追跡する必要があります。http://jsfiddle.net/pimvdb/5L9FN/

    var randomdiameter = 100*Math.random()+100; //random diameter
    var randomTop = 400*Math.random(); //random top position
    var randomLeft = 350*Math.random(); //random left position

    while(overlapping(randomTop + randomdiameter / 2,  // x midpoint
                      randomLeft + randomdiameter / 2, // y midpoint
                      randomdiameter / 2)) { // radius
        // generate again if overlapping any other image
        randomTop = 400*Math.random(); //random top position
        randomLeft = 350*Math.random(); //random left position
    }

    images.push([randomTop + randomdiameter / 2, 
                 randomLeft + randomdiameter / 2, 
                 randomdiameter / 2]); // push this image in the array

次に、重複を確認するために、2 つの中点それぞれの間の距離を計算し、2 つの半径よりも小さいかどうかを確認できます。

var images = [];

function overlapping(x, y, r) {
    for(var i = 0; i < images.length; i++) { // iterate over all images
        var im = images[i]; // this image

        var dx = im[0] - x; // x distance between this image and new image
        var dy = im[1] - y; // y distance between this image and new image

        if(Math.sqrt(dx*dx + dy*dy) <= im[2] + r) {
            // if distance between midpoints is less than the radii, they are overlapping
            return true;
        }
    }
    return false; // when we reach this point the new image has not been overlapping any
}
于 2011-08-22T13:32:20.070 に答える