iio.js Random Animation

This tutorial shows how to create a randomized animation with JavaScript, HTML5, and iio.js

Setup

A text editor will be needed to edit code. Any editor similar to Sublime Text will work.

If you want a local copy of iio.js, download the iio.min.js build file. You can get that file here or get it on Github.

Otherwise, you can load the file from the web:

"http://iio.js.org/iio.min.js"

Initialize the App

Create a new HTML file called ColorGrid in a folder with the iio.min.js JavaScript file.

Open the HTML file in a text editor and input this code:

<!doctype html>
  <body>
    <script type="text/javascript" src="iio.min.js"></script>
    <script type="text/javascript">

        ColorGrid = function( app ){

          // application code...

        }

        // start ColorGrid fullscreen
        iio.start( ColorGrid );
    
    </script>
  </body>
</html>

This code defines an HTML document, loads in iio.js, then initializes the app's main application function.

iio.start creates a fullscreen canvas and starts the app.

Let's begin by turning the background black. Put this code where the '// application code' comment is:

// set app background to black
app.set({ color: 'black' });

Now add a shape to the application. For a full list of possible shapes, checkout the documentation. In this tutorial, we will create a square with a random color using the Quad shape:

// add a new Quad to app
app.add( new iio.Quad({
  pos: app.center, // sets position to app center
  width: 100,      // sets width to 100px
  // height: 100,  // defaults to width value if undefined
  color: iio.Color.random(),
}));

iio.Color.random() - a static function call that returns a random Color object.

(this one is always red though, because it looks nice)

Next, lets animate the square by making it shrink:

app.add( new iio.Quad({
  //...
  shrink:{
    speed: .05,
    // called when the square is too small to see
    callback: function(square){
      square.set({
        width: 100,
        height: 100, // height also needs to be reset
        color: square.color.randomize()
      });
    }
  }
});

The square will now shrink at a rate of .05px / 60 times a second until it is too small to be seen, then the callback is run. If no callback is provided, the object is removed from app.

This callback sets the width and height of the square to their initial values. It also changes the color to a new random one using the previously set Color object's randomize function.

Now, it may feel strange to have to set the square's color indirectly instead of letting its randomize function do all the work, and you're right its strange.

I used set because it allows object manipulation with the same syntax as in object creation.

new iio.Quad({//... object creation example

However, it is inefficient for repeated object manipulation, and really should only be used in object creation, or non-animating applications.

The best practice approach is to change the properties directly:

  shrink:{
    //...
    callback: function(square){
      square.width = square.height = 100;
      square.color.randomize();
    }
  }

Ok let's make a grid of squares instead of just one. This can be accomplished with variables and loops.

First, at the top of the application function, assign a variable to a constant value equal width of the square:

var WIDTH = 100; // all caps for variables that don't change
                // called 'constants'

Now replace the hard coded "width" values with WIDTH and put the Quad creation code into two loops that iterate through rows and columns:

for(var column = WIDTH/2; column < app.WIDTH; column++)
  for(var row = WIDTH/2; row < app.WIDTH; row++)
    app.add( new iio.Quad({
      pos: [column, row],
      width: WIDTH,
      color: iio.Color.random(),
      shrink: {
        speed: 0.05,
        callback: function(square){
          square.width = square.height = WIDTH;
          square.color.randomize();
        }
      }
    }));

Pretty cool already but let's introduce more randomness. Instead of keeping all the squares in sync, make them shrink at different speeds.

The iio.random function makes this easy:

      //...
        // set the speed to a random number between .05 and .2
        speed: iio.random(.05, .2),
        //...

Try changing the value of WIDTH and other variables or initialization values to change up the animation.

I set WIDTH = 20 and set all squares' colors to 'white' instead of a random color to create my final version.

Before wrapping it up and shipping it, there is one more change we can make for better efficiency.

app.add both adds an object to app and redraws the canvas by default. That means that the canvas gets drawn again after every single square added - very unnecessary since we have a looping animation running that already redraws the canvas.

To fix this, we can pass a boolean flag to prevent app.add from redrawing:

  //...
    app.add( new iio.Quad({
      //...
    }, true)); // pass true to suppress redraw

Much better. Here's the final app.

And the final code. I shortened the variable names for better readability.

<!doctype html>
  <body>
    <script type="text/javascript" src="iio.min.js"></script>
    <script type="text/javascript">

      ColorGrid = function( app ){

        app.set({ color:'black' });
        var w = 20;

        for( var c = w/2; c < app.width;  c += w )
        for( var r = w/2; r < app.height; r += w )
          app.add( new iio.Quad({
            pos: [c,r],
            width: w,
            color: 'white',
            shrink:{
              speed: iio.random(.05,.2),
              callback: function( square ){
                square.width = square.height = w;
                square.color.randomize();
              }
            }
          }), true);
      }

      // start the app fullscreen
      iio.start( ColorGrid );

    </script>
  </body>
</html>

getting help

If you need help with setup or have a question/issue with the source code, post a query via Github