Pergunta

I have two circles. one is with 150 radius and other one is 350 radius. I want to place number of circles in between space of 150 - 350 radius. It shouldn't be over-placed(overwrite) on other circle which is already placed. It should be placed randomly on every refresh. Can some one please give me idea/logic of how to do this in canvas. Javascript.

Sample Image red question mark circle I wanted to place

[EDIT]

  1. Radius of all circles are predefined.
Foi útil?

Solução 2

A Demo: http://jsfiddle.net/m1erickson/aGq8p/

enter image description here

The trick here is to create random circles but also to be sure they don't overlap previously created circles.

Here's annotated code:

function randomCircle(){

    // define random radius

    var radius=minCircle+Math.random()*(maxCircle-minCircle);

    // define random distance between inner/outer rings

    var distFromCenter=innerRadius+radius+Math.random()*(outerRadius-innerRadius-radius*2);

    // define random angle

    var angle=Math.random()*PI2;

    // calculate the x,y of the defined circle

    var x=cx+distFromCenter*Math.cos(angle);
    var y=cy+distFromCenter*Math.sin(angle);

    // check this new circle versus all previous random circles for a collision 

    var hit=false;
    for(var i=0;i<randomCircles.length;i++){
        var circle=randomCircles[i];
        var dx=circle.cx-x;
        var dy=circle.cy-y;
        var r=circle.radius+radius;
        if(dx*dx+dy*dy<=r*r){
            hit=true;
        }
    }

    // if no collision occurred, add this new circle to the existing circles array

    if(!hit){
        var color=randomColor();
        randomCircles.push({cx:x,cy:y,radius:radius,color:color}); 
    }

}

Outras dicas

As for drawing the actual images, that's up to you, but here's how you place the circles:

First, pick a Θ, at random, between 0° and 360°.

Then pick a radius r1 for your little circle, between 0 and 50 (half of the 100-pixel width of the "track").

Then pick a center location r2, between 150 + r1 and 350 - r1.

Now draw a circle radius r1 at the location given in polar coordinates by (Θ, r2).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top