Online Book Reader

Home Category

HTML5 Canvas [81]

By Root 6480 0
the radius, centerX, and centerY properties of the circle path object.

Example 5-9 shows the code for CH5EX9.html.

Example 5-9. Moving in a circle

CH5EX9: Moving In A Circle

Your browser does not support HTML5 Canvas.

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-13, 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-13. Moving an object in a simple spiral pattern

Example 5-10. Moving in a simple geometric spiral

CH5EX10: Moving In A Simple Geometric Spiral