Michael Ben-Nes
Michael Ben-Nes

Reputation: 7645

spread HTML elements randomly over a div using JavaScript

I wish to create something like a virtual forest.

I have:

How can I spread the trees so they:

Thanks

More info as requested:

I created the following php script, but it does not handle the empty location nor its accurate in fitting the images into the div:

$forest1 = null;
for ($a=1; $a < 201; $a++) {

    // width * height (500*280)
    $total_area_in_pixels = 140000;
    $total_elements = 200;
    $area_per_object = $total_area_in_pixels / $total_elements;
    $element_height = round (sqrt($area_per_object) / 100 * 70);

    $random_margin = rand(0, $element_height / 5);
    $tree_type = rand(1,4);
    $style = "height: {$element_height}px; margin: {$random_margin}px;";
    $forest1 .= "<img src='images/trees/tree{$tree_type}.png' alt='{$a}' title='tree' style='{$style}'>\n";
}

Upvotes: 1

Views: 785

Answers (1)

JamesHoux
JamesHoux

Reputation: 3457

You need to figure out how you want to do the positioning first. You can either set the trees absolutely based on the div parent as a container, or you can position the trees absolutely based on the entire page as a container.

To use the parent as a container, you would do this: Set the div to position: relative. Write javascript to create IMG elements and then set their position to 'absolute'. Make sure that when you create the elements you create them as child elements of the DIV you want to contain them.

TO use the page as a container, you would do this: Write javascript to create IMG elements and set their position to 'absolute'. Don't bother making them child elements of the DIV because it doesn't matter. Use jQuery or a basic javascript test to find out the exact page position of the container div. Everytime you place a tree, you will need to calculate its position with respect to the container div.

Position trees basically like this: Write a simple algorithm to generate random x and y coordinate pairs to position each element and do so. Then check each tree's position and width and height against the square area you don't want to be covered. If you find a tree in that area, either move it some to get it out of the area, or delete it. Just make sure to remember that if you're positioning absolutely within the whole page, you'll always have to add or subtract the page container position as an offste to get the trees where you want them on the page.

That should be enough to get you started.

Upvotes: 2

Related Questions