Search code examples
javascriptjqueryspiral

drawing spiral using jquery - spot distance


I am trying to draw a spiral from divs using jquery. I have done a regular spiral so far and seems to work fine for me. However the next step is that I need this to have big distance between divs when it starts and smaller one as it goes. I know that I should add an extra variable that will do this but I do not know how to implement this.

Here is my code so far

var radius = 50;
var x0 = 300;
var y0 = 300;
var segment = 50;
var angle = 0;    

for (var i=0; i<=segment; i++){
  angle = angle + (Math.PI * 2) / 30;
  var x=x0+radius*Math.sin(angle);
  var y=y0+radius*Math.cos(angle);
  $("#terrain").append("<div class='drag' style='top:"+ y +"px;left:"+ x +"px;'></div>")
  radius = radius + 5;   
}

jsfiddle


Solution

  • You could make the size of each div a function of the radius. One-seventh seems to work well:

    size = radius/7;
    $("#terrain")
      .append("<div class='drag' style='top:"+ y +"px;left:"+x+
              "px;width:"+size+"px;height:"+size+"px;'></div>"
             );
    

    Working Fiddle


    Edit

    Based on our comments, I now understand the problem better. You could declare a distance variable, which is the distance between divs. angle would then be updated as:

    angle += distance/radius;
    

    Each time through the loop, the distance would decrease, like this:

    distance -= 1.5;
    

    The rest of your code stays pretty much the same.

    Working Fiddle