Scene, State and StateMachine

The goal of State and StateMachcine is providing an ability to create some sort of "scenes" for your demos. Scenes are kind of finite-state automata.


Scene is a simple container, an entity containing "init" and "draw" methods. It has no magic, for it is merely a set of event listeners and functions.

The idea is this: you create a scene object, define its init and draw handlers, and then call its "draw" method. It will automatically call the init first time it is drawn to initialize whatever needs to be initialized.

Scene itself is passed to handlers as this and first argument.

The scene object itself can be passed to cdf.animate function.

var scene = new cdf.Scene();

  // d here is link to scene itself. You can add attributes to d
  // or to 'this' variable, which also contains the scene.
  // The scene is used as some sort of "payload"

  this.canvas = cdf.c(57,25);  // Create and store canvas in d.c
  this.n = 0;                  // Store empty integer

  // On canvas click - toggle pause state of the scene
  this.canvas.element.addEventListener('click', function () {
    // This one also accepts true/false for play state


    .text(this.n++,,, '#F00',0,'center','middle');

// scene.animate is a function that calls "draw" method, ut only
// in case the scene is not paused


All methods of scene are chainable

These methods can also be chained to create more compact and eloquent code:

cdf.animate(new cdf.Scene()
  .on('init', function(scene){
    scene.canvas = cdf.c(400,400);
    scene.stars =  new cdf.starfield3D(scene.canvas,500);
  .on('draw', function(scene){