Frame Based Animation

Simple program to show how frame based animation can affect a game.

by Steven Lambert

HTML

<canvas id="canvas60" width="200" height="200"></canvas>
<canvas id="canvas30" width="200" height="200"></canvas>
<canvas id="canvas10" width="200" height="200"></canvas>

CSS

canvas {
    border: 1px solid;
    margin: 10px;
    float: left;
}

JavaScript

var canvas60 = document.getElementById('canvas60');
var canvas30 = document.getElementById('canvas30');
var canvas10 = document.getElementById('canvas10');
var ctx60    = canvas60.getContext('2d');
var ctx30    = canvas30.getContext('2d');
var ctx10    = canvas10.getContext('2d');

ctx30.fillStyle = '#0000DD';
ctx10.fillStyle = '#DD0000';

var square60 = {'x': 50, 'y': 50, 'dx': 2, 'dy': 1, 'width': 10, 'height': 10};
var square30 = {'x': 50, 'y': 50, 'dx': 2, 'dy': 1, 'width': 10, 'height': 10};
var square10 = {'x': 50, 'y': 50, 'dx': 2, 'dy': 1, 'width': 10, 'height': 10};

var sixtyFPS = (function(){
    return function(callback, element){
        window.setTimeout(callback, 1000 / 60);
    };
})();

var thirtyFPS = (function(){
    return function(callback, element){
        window.setTimeout(callback, 1000 / 30);
    };
})();

var tenFPS = (function(){
    return function(callback, element){
        window.setTimeout(callback, 1000 / 10);
    };
})();

function animate60() {
    sixtyFPS( animate60 );
    
    ctx60.clearRect(0, 0, canvas60.width, canvas60.height);
    
    square60.x += square60.dx;
    square60.y += square60.dy;
    
    if (square60.x <= 0 || square60.x >= canvas60.width - square60.width)
        square60.dx = -square60.dx;
    
    if (square60.y <= 0 || square60.y >= canvas60.height - square60.height)
        square60.dy = -square60.dy;
    
    ctx60.fillRect(square60.x, square60.y, square60.width, square60.height);
};

function animate30() {
    thirtyFPS( animate30 );
    
    ctx30.clearRect(0, 0, canvas30.width, canvas30.height);
    
    square30.x += square30.dx;
    square30.y += square30.dy;
    
    if (square30.x <= 0 || square30.x >= canvas30.width - square30.width)
        square30.dx = -square30.dx;
    
    if (square30.y <= 0 || square30.y >= canvas30.height - square30.height)
        square30.dy = -square30.dy;
    
    ctx30.fillRect(square30.x, square30.y, square30.width, square30.height);
};

function animate10() {
 ...