views:

370

answers:

2

What is the algorithm for storing the pixels in a spiral in JS?

+2  A: 

There are a couple of problems with this question. The first is that you're not really being specific about what you're doing.

1) Javascript isn't really a storage medium, unless you're looking to transmit the pixels using JSON, in which case you may want to rephrase to explicitly state that.

2) There's no mention of what you expect the spiral to look like - are we talking about a loose spiral or a tight spiral? Monocolor or a gradient or a series of colors ? Are you looking at a curved spiral or a rectangular one?

3) What is the final aim here? Are you looking to draw the spiral directly using JS or are you transmitting it to some other place?

Mike Burton
+2  A: 

http://www.mathematische-basteleien.de/spiral.htm

var Spiral = function(a) {
    this.initialize(a);
}

Spiral.prototype = {
    _a: 0.5,

    constructor: Spiral,

    initialize: function( a ) {
       if (a != null) this._a = a;
    },


    /* specify the increment in radians */
    points: function( rotations, increment ) {
       var maxAngle = Math.PI * 2 * rotations;
       var points = new Array();

       for (var angle = 0; angle <= maxAngle; angle = angle + increment)
       {
          points.push( this._point( angle ) );
       }

       return points;
    },

    _point: function( t ) {
        var x = this._a * t * Math.cos(t);
        var y = this._a * t * Math.sin(t);
        return { X: x, Y: y };
    }
}


var spiral = new Spiral(0.3);
var points = spiral.points( 2, 0.01 );

plot(points);


Sample implementation at http://myweb.uiowa.edu/timv/spiral.htm

tvanfosson
Archimedian spiral... Adjust the _point function for other types.
tvanfosson