Moving in a Simple Spiral

There are many complicated ways to move an object on a spiral path. One such way would be to use the Fibonacci sequence, which describes a pattern seen in nature that appears to create perfect spirals. The Fibonacci sequence starts with the number 0, and continues with each subsequent number calculated as the sum of the two previous numbers in the sequence. Each subsequent rotation of the spiral is the sum of the two previous numbers (1, 2, 3, 5, 8, 13, 21, 34, 55, 89...). However, as you might imagine, the math used to create this sequence is quite involved, and it is also difficult to translate to object movement.

For our purposes, we can create a simple spiral by increasing the radius of the circle path on each call to drawScreen(). If we take the code from Example 5-9, we would add a radiusInc variable, which we will use as the value to add the radius movement path of the circle. We create this new variable in canvasApp():

var radiusInc = 2;

Then, in drawScreen(), we add the following code to increase the radius of the circle every time we move the object:

circle.radius += radiusInc;

In Figure 5-14, you can see what the resulting spiral looks like. (To illustrate the path, this example includes the points.)

If you want a tighter spiral, decrease the value of radiusInc. Conversely, if you want a wider spiral, increase the value of radiusInc.

Example 5-10 shows the code for CH5EX10.html from the code distribution.

Figure 5-14. Moving an object in a simple spiral ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.