Javascript game development 7: animations and sprites

With this chapter, I will expand our html5 game engine with a new object: the sprite. The sprite uses the images from the graphics module and has its own timer for handling an animation. It controls its position itself and provide a own drawing method. The sprite can be instanced, because multiply sprites with the same sets of images may differ in the animation state and speed.
Later, it would be a nice feature to allow the use of sprite sheets instead of single images. Just as implementing the ability to use multiple animations in one sprite.
Result of this chapter

download chapter


(function() {
    window.objects.sprite = (function sprite(data) {
        //data is an object that holds the initial values
        this.images = data.images;
        this.frameTime = data.frameTime;
        this.frame = 0;
        this.frameCount = this.images.length;
        this.lastTick = 0;
        this.position = new window.objects.vector();
    var sprite = window.objects.sprite.prototype;
    sprite.draw = (function() {
        //draw the actual animation frame
        var stamp =;
        //check if its time to increase the frame
        if(stamp - this.lastTick >= this.frameTime)
            if(this.frame >= this.frameCount)
                this.frame = 0;
            this.lastTick = stamp;

The main.js has completely changed for testing the object.


window.modules.main = (function($) {
    return {
        init: (function() {
             * instances a new sprite
             * array of image names from the graphics module
             * time between frames in milliseconds
            this.monkey = new window.objects.sprite({
                images:  ["monkeya", "monkeyb", "monkeyc"],
                frameTime: 100
        loop: (function() {
            var modules = window.modules;
            var objects = window.objects;
            //"this" would be window because the request animation frame
            //so let's make our own "this"
            var _this = modules.main;
            //set sprite position and let it draw
            _this.monkey.position.x(320 / 2 - 24);
            _this.monkey.position.y(240 / 2 - 20);


//add the sprite object for loading
var objects = [

For creating the animation I used thee sprite sheet below. I cut out single frames. I think the “monkey” is jumping. This sheet is part of the spritelib (gpl).