Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random element position and prevent overlapping in JavaScript

Tags:

I have a holder div on the page where I want to load small images in on random position as a collage with 10px padding on each.

How can I make sure that images never overlap each other or holder div? Is there a plugin or function that I could use?

My code so far:

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function(){
$("#my_canvas img").each(
function(intIndex) {

var l = Math.floor(Math.random() * $("#my_canvas").width());
var t = Math.floor(Math.random() * $("#my_canvas").height());

$(this).css("left", l);
$(this).css("top", t);

$(this).bind(
    "click",
        function() {
            alert("l=" + l + " t=" + t);
        }
    );

}

);

});

   <style type="text/css">
    #my_canvas
    {
        background: #eee;
        border: black 1px solid;
        width: 800px;
        height: 400px;
    }
    #my_canvas img
    {
        padding: 10px;
        position:absolute;
    }
</style>

<div id="my_canvas">
    <img src="images/1.jpg" />
    <img src="images/9.jpg" />
    <img src="images/2.jpg" />
    <img src="images/3.jpg" />
    <img src="images/4.jpg" />
    <img src="images/5.jpg" />
    <img src="images/6.jpg" />
    <img src="images/7.jpg" />
    <img src="images/8.jpg" />
</div>
like image 592
jpkeisala Avatar asked Aug 17 '09 08:08

jpkeisala


1 Answers

Store the picked coordinates in an array, so that you can compare the coordinates of each new image you place against the previous.

If the coordinates that you picked overlaps a previous image, pick new coordinates. Limit the number of tries so that if you can't place an image with say 1000 tries, you start over with the first image.

like image 182
Guffa Avatar answered Oct 06 '22 16:10

Guffa