Introduction to Canvas - Animation

The code for this tutorial can be found here. You can also see a working version of the code here.

HTML

The html file is fairly straightforward – I’ve included the javascript files referenced in the <head> section. The most important part of this file (other than remembering to include the javascript) is the <canvas> tag. This is where we are going to be doing all the drawing. The <body> onLoad() calls the loadGame() function which is in the FiltoidGameLoop javascript file.

FiltoidGameLoop and the Game Loop

The main part of any game or animation is the concept of the game loop. The loop keeps going for the lifetime of the game and does the updating of the game (move on animations/calculate game logic like bullets and firing) and also does the drawing (rendering each frame). In the FiltoidGameLoop code the game loop is created in the loadGame function and this is where we will call through to our update and draw methods.

Rotating Square

Looking at the code we can see that the Square.js code offers the actual functionality and slots into the FiltoidGameLoop to produce the rotating output. The setup should be fairly straightforward to understand. The rotation code in the sqUpdate() function is also fairly straightforward.

Drawing the Square

The drawing of the square is really the grunt work of the function. Drawing a square in html is fairly straightforward but when we have to be able to draw it rotated then it gets more complicated. We need to figure out the points based on a rotation then connect them up. Fortunately it’s fairly straight forward to handle. We can plot the points on a unity circle using radians and some geometry.

If you plot a graph with for all angles (theta) between 0 and 2*PI and use Sin(theta) to plot the x co-ordinate and Cos(theta) for the y then you get a circle. This means that as we increase theta we can find a point moving around a circle.

Our squares starting rotation of 0 is directly up (although because the y axis on a screen is inverted (the greater the y the further down the screen) this mean pointing down. We can figure out the points by dividing the circle evenly 4 times and offset it so that the starting point and last point on the circle are the same y value. This results in the angles that we need being (PI/4),(3*PI/4),(5*PI/4) and (7*PI/4). We calculate our points based on these angles + the angle of rotation for the square. Once we have these coordinates then we need to translate the entire thing to location of the square (this.loc) and then connect the points with lines to complete the process.