Sunday, October 9, 2011

HowTo: Canvas colorful bouncing circle animation with JavaScript

Introduction


I've really really waited for the moment when I can start developing canvas animations. In this post I'm going to present you what I've coded and tell you a few words about its concept.

But, check out the Demo first.

So, as you've seen, the result is a canvas with bouncing and colorful circles. They are random positioned with random colors, random directions and random sizes. But, what is a canvas? Canvas is a part of Html5 specification. You can use it to draw graphics and animations with the help of JavaScript.

<canvas width="400" height="300"></canvas>

I won't go into basics of canvas element. If you are interested about it, please check out Mozilla Developer Network's Canvas Tutorial.

Animation basics

Frames. All we need is them. A frame is a 'screenshot' of the current state of a scene. A scene contains the objects and pretty much everything we want to draw to the audience. We create an animation from frames by drawing at least 24 to the screen in every second. This is the minimum amount to deceive the eye to see motion on the screen. Of course, the more frames we draw in one second, the smoother the animation gets. From frame to frame we must update and redraw all of the objects. Everytime we create an animation the following things happen:
  1. Initialization
  2. Updating scene
  3. Drawing scene
  4. While it must be drawn, jump back to the 2. point else 5.
  5. End of animation

The 2., 3. and 4. point together forms the main loop. This is where all of the scene objects' state, position, color etc. gets updated and gets drawn. If you wish to put user input to the animation (etc, mouse movement) there would be a new item in the list for input handling.

Skeleton of my animation object

var animation = function() {
 /* List of objects to draw (the particles) */
 var list = [];

 /* Frame per seconds */
 var fps = 24;

 /* Object constructor */
 var particle = function() {};
 
 /* Initialization */
 this.init = function(v) {};

 /* Updating objects state, position, etc.. */
 var update = function() {};

 /* Drawing the objects */
 var draw = function() {};

 /* Calling update() and draw() */
 var loop = function() {};

 /* Setting main loop */
 this.play = function() {};
}

The above source snippet is the skeleton of my animation object.

Initialization

Bouncing circles on the screen represented as a particle object. The animation itself has a variable called list. Every item of it will be a new particle object. Calling the init() function with a number parameter will add as much particles to the animation as much we want.

Particles

Particles object looks like this:
/* Particle object */
  var particle = function() {
    /* Coordinates */
    this.x = 0;
    this.y = 0;

    /* The radius of circles */
    this.radius = 5;

    this.speed_x = 1;
    this.speed_y = 1;

    /* Direction */
    this.dx = 0;
    this.dy = 0;

    this.color = {
      fill : '#000',
      stroke : '#000'
    }

    /* Boundaries (canvas width and height) */
    this.bounds = {
      x0 : 0,
      x1 : 600,
      y0 : 0,
      y1 : 400
    }

    /* Private function for random color but I think you've already guessed that. */
    var random_color = function(){}

    /* Function to initialise variables */
    this.init = function() {}

    /* Updater function, called at every frame. It updates positions and check boundaries. */
    this.update = function() {}
  }

To represent a circle on the screen I stored information about it such as its x and y coordinate, its x and y speed, its direction, its colors and its boundaries because I don't want it to go away from the screen leaving a blank white field to the user. Init function sets variables to random values. The update function is used to update the circles properties in every loop. It will be called by the loop's update function.

Updating and drawing

I've defined a loop function. It simply calls the update() and draw() once. To create the animation by calling the loop function multiple times in every second I have to use the setInterval() function.

/* To start animation */
this.play = function() {

 /* Animloop */                        
 setInterval(loop, 1000/fps);          
      
};

The first parameter must be a function what will be called, and the second parameter must be a number representing a ms value. Let's say I want it to call 24 times a second, then I must divide 1000 by the fps rate (24 now) to get the desired ms values.


var ANIM = new animation();
ANIM.init(25);
ANIM.play();

Final words

This is a basic animation concept. I hope you found it useful. Play with it online on this link at JsFiddle.net. If you would like to say anything or noticed something, please leave a comment.

1 comment:

  1. If any one thought about doing something like this in the background here is some code to help do that. Technically you would only need to add a few lines of code to your existing html and css file and import the js.
    http://jsfiddle.net/se9vV/1/

    ReplyDelete