Search code examples
javascriptjqueryhtmlcsspositioning

positioning elements randomly in a circle


i'm writing a fastfood app , basically allowing users to custom their pitza by adding stuff to it .

so , i show a simple pitza to them and on the sidebar they have all this stuff ... like pepperoni , beef , mushroom and ...

<div id = "pitz" style="background-image: url("pitza.png");" > </div>

<div class="custom" id="pepperoni">peppeoni</div>
<div class="custom" id="beef">beef </div>
<div class="custom" id="mushroom">mushroom </div>

so when user clicks on the custom divs like mushroom i want to add little mushrooms to my pitza ... something like

$('.custom').click(function(e) {

    var backgroung = $(this).attr('id')+'.png';

    for( i = 0 ; i < 40 ; i++ )
    {
        var top , left = i ;

        var add = '<div style="top:'+top+'px ; left:'+left+'px ; width:100;height:100px;background-image:url("'+background+'");" ></div>';
        $('#pitza').append(add);
    }

});

so here is the problem , in order to add little items (mushrooms) to my parent item (pitza) i need to position them ... in this case in a circle (pitza) so i need to generate random position for each item so they don't overlap also these positions should be in a imaginary circle and it should cover all parts of circle , i dont want left side empty and right side full of mushrooms .

obviously this doesn't work and i have no idea how to do it :

for( i = 0 ; i < 40 ; i++ )
{
    var top , left = i ;

Solution

  • Basically you're looking at two circles, one with the radius of your pizza, and one with the radius of your topping. So you'd do something like this.

    var pizzaRadius = 200,
        toppingRadii = {
            mushroom: 40,
            pepperoni: 50,
            onions: 25
        };
    
    function getToppingPosition(toppingRadius){
       var posX, posY;
       do {
           posX = Math.floor(Math.random() * ((pizzaRadius * 2) - 1));
           posY = Math.floor(Math.random() * ((pizzaRadius * 2) - 1));
       } while(Math.sqrt(Math.pow(pizzaRadius - posX, 2) + Math.pow(pizzaRadius - posY, 2)) > pizzaRadius - toppingRadius)
    
       return { x: posX, y: posY }
    }
    

    Basically what that function does is gets a random number within the bounds of the pizza and makes sure that the position + the size of the topping is on the pizza (so there's no toppings hanging over the edge. After that you'd just plug that function into your loop

    $('.custom').click(function(e) {
    
        var backgroung = $(this).attr('id')+'.png',
            topping = 'mushroom';
    
        for( i = 0 ; i < 40 ; i++ )
        {
            var pos = getToppingPosition(toppingRadii[topping])
    
            var add = '<div style="top:'+pos.x+'px ; left:'+pos.y+'px ; width:100;height:100px;background-image:url("'+background+'");" ></div>';
            $('#pitza').append(add);
        }
    
    });
    

    Here's a fiddle http://jsfiddle.net/19h242yc/