How to Use the Animation Loop on JavaScript’s Canvas for HTML5 and CSS3 Programming - dummies

How to Use the Animation Loop on JavaScript’s Canvas for HTML5 and CSS3 Programming

By Andy Harris

An animation in JavaScript generally requires a special organization called an animation loop. The basic structure of the animation loop in HTML5 and CSS3 programming works the same in any language:

  1. Initialization.

    Create the assets, including the background and any of the objects you will be using. Objects that will be manipulated in real time are normally called sprites. Generally this is done when the program first runs, to save time during the main execution. You may also set constants for image size, display size, frame rate, and other values that will not change during the execution of the game.

  2. Determining a frame rate.

    Animations and games work by calling a function repeatedly at a prescribed rate. In general, you’ll have some sort of function that is called repeatedly. In JavaScript, you typically use the setInterval() function to specify a function that will be called repeatedly.

    The frame rate indicates how often the specified function will be called. Games and animations typically run at frame rates between 10 and 30 frames per second. A faster frame rate is smoother, but may not be maintainable with some hardware.

  3. Evaluating the current state.

    Each sprite is really a data element. During every frame, determine if anything important has happened: Did the user press a key? Is an element supposed to move? Did a sprite leave the screen? Did two sprites conk into each other?

  4. Modifying sprite data.

    Each sprite generally has position or rotation data that can be modified during each frame. Usually this is done through transformations (translation, rotation, and scale), although sometimes you may switch between images instead.

  5. Clearing the background.

    An animation is really a series of images drawn rapidly in the same place. Usually you’ll need to clear the background at the beginning of each frame to clear out the last frame’s image.

  6. Redrawing all sprites.

    Each sprite is re-drawn using its new data. The sprites appear to move because they’re drawn in a new location or orientation.