Search code examples
createjseaseljs

Creating Shapes Where No Others Exist


I am trying to think of a way to create shapes where others don't exist, using CreateJS. I'm not quite sure where to start or what even to search for in this case. Basically, my goal is have circles appear on the stage, but only where others aren't.

My question is, what is a good way to approach this? Is there any documentation or similar that could help me achieve create the code to do this?

Link to JSFiddle

var stage = new createjs.Stage("canvas"),
    canvas = stage.canvas;

function createCircle(){
    var circle = new createjs.Shape().set({name:"circle"});    
    circle.graphics
        .beginFill("DeepSkyBlue")
      .drawCircle(0, 0, 25);
    circle.x = Math.random() * canvas.width;
        circle.y = Math.random() * canvas.height;    
    stage.addChild(circle);
}

setInterval(function(){ 
    createCircle();
  stage.update();
  }, 1000);

Solution

  • Here is a really simple demo that populates circles, ensuring they do not touch.

    1. Generate a random circle size
    2. Pick a random x/y
    3. Check the distance from other circles
    4. If it is not touching, draw the circle at that point. If it does touch, try again

    http://jsfiddle.net/lannymcnie/2o7do8kf/1/

    // Basic distance checking
    var circle = circles[i], 
      dX = circle.x - x, 
      dY = circle.y - y,    
      dist = Math.sqrt(dX*dX + dY*dY);
    if (dist <= size + circle.size) {
      ok = false; 
      break;
    }
    

    This demo will try 100 times (max) to position each circle. If it ever runs over 100, it will give up completely. You can increase this to 10,000 and it basically gets the same result.

    This is obviously not the most efficient or complicated way to do this, but it might get something close enough to what you are looking for without getting crazy.