2

我有一个画廊,其中的图像经受了粗暴的处理:它们的大小和位置随机放置在一个容器中。此外,它们是四舍五入的,只需单击鼠标即可更改大小。请放心,它实际上比听起来要简单得多。

好的,这是我的意思的(可爱的)示例:http: //dl.dropbox.com/u/5550635/Test%20rounded%20gallery/example2.htm

我的问题在这个例子中非常明显,图像大部分时间都是重叠的。
当您单击其中一个图像时,同样的事情,其他图像下降,并且应该形成一条不重叠的线,它们之间可能至少有 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 解决方案来防止图像重叠,但我找不到适合我的具体情况的解决方案。如果您只是看看我的问题并分享您的一些科学知识,我将非常感激。谢谢!

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

然后,要检查重叠,您可以计算每两个中点之间的距离并检查它是否小于两个半径:

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 回答