Search code examples
javascripthtmlmathcanvaskineticjs

How to draw circle at random position in between of two circles?


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.

Solution

  • 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}); 
        }
    
    }