Kinetic Animation Demo

Not fully functioning

by klenwell

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/kineticjs/5.0.6/kinetic.js"></script>
<div id="app-stage"></div>
<button id="start-animation">start</button>
<button id="stop-animation">stop</button>

CSS

div#app-stage .kineticjs-content {
  margin:0 auto;
  background-color:#EEEEEE;
  border:1px solid #DDDDDD;
}

JavaScript

// http://jsfiddle.net/klenwell/JvG2Z/

function Simulation() {
    var self = {};
    
    // Constants
    var SIM_WIDTH = 400,
        SIM_HEIGHT = 300;
    
    self.world = null;
    self.organisms = [];
    self.stage = null;
    self.root_layer = null;
    self.animation = null;
    
    self.init = function() {
        self.init_kinetic();
        self.init_world();
        self.init_organisms();
        self.init_buttons();
    };
    
    self.init_buttons = function() {
        var start_button = document.getElementById('start-animation');
        var stop_button = document.getElementById('stop-animation');
        
        start_button.addEventListener("click", function() {
            self.animation.start();
            console.debug('simulation started');
        }, false);
        
        stop_button.addEventListener("click", function() {
            self.animation.stop();
            console.debug('simulation stopped');
        }, false);
    };
    
    self.init_kinetic = function() {
        self.stage = new Kinetic.Stage({
            container: 'app-stage',
            width: SIM_WIDTH,
            height: SIM_HEIGHT
        });
        self.root_layer = new Kinetic.Layer();
        self.animation = new Kinetic.Animation(self.update, self.root_layer);
        self.stage.add(self.root_layer);
        return self;
    };
    
    self.enable_auto_screen_resize = function() {
        // See http://stackoverflow.com/q/17468180/1093087
        // Make sure you use constants (i.e., SIM_WIDTH and SIM_HEIGHT). Using
        // stage.getWidth() does not work because browser calculates on the fly
        // and basically rounds to 1.0.
        var resize_callback = function() {
            var screen_width = window.innerWidth;
            var screen_height = window.innerHeight;
            var x_scale = screen_width / SIM_WIDTH;
            var y_scale = screen_height / SIM_HEIGHT;
            
            // find optimal ratio
            var...