O'Reilly logo

HTML5 Canvas Cookbook by Eric Rowell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a Model class

In this recipe, we'll create a Model class which is responsible for initializing and updating the hero, the bad guys, the level, and the health bar. These objects can be seen as the "data" of our game.

How to do it...

Follow these steps to create the model for Canvas Hero:

  1. Define the Model constructor:
    /*
     * Game model
     * 
     * The model is responsible for initializing and
     * updating the hero, level, bad guys, and health bar
     */
    function Model(controller){
        this.controller = controller;
        this.healthBar = null;
        this.hero = null;
        this.level = null;
        this.badGuys = []; // array of bad guys
        this.heroCanvasPos = {};
    }
  2. Define the removeDefeatedBadGuys() method which loops through the bad guy array and then removes the ones that are no longer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required