Javascript:防止在随机大小的图像上重叠

时间:2011-08-22 13:17:22

标签: javascript jquery image overlapping

我有一个画廊,其中的图像经受了粗略的处理:它们的大小和随机放置在一个容器中。它们也是四舍五入的,并且通过鼠标点击改变大小..可以放心,它实际上比听起来简单得多。

好的,这是一个(可爱的)我的意思的例子: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解决方案,以防止重叠的图像,但我找不到符合我的特点。 如果您只是看看我的问题并分享您的科学知识,我将非常感激。谢谢!

1 个答案:

答案 0 :(得分: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
}