FrozenJS Image Loading Example

Simple demo that shows how to load images through an AMD plugin. Oh, and it lets move the nyan cat around the screen :)

by monteslu

HTML

<script src="http://rawgithub.com/iceddev/frozen/master/dist/frozen.js.uncompressed.js"></script>
<div id="gameArea">
    <canvas id="canvas" width="692" height="395"></canvas>
</div>

CSS

body {
    background-color: #222;
    color: #fff;
    margin: 0 auto;
}
#gameArea {
    margin: 10px;
}

JavaScript

//load the AMD modules we need
require([
  'frozen/GameCore',
  'dojo/keys',
  // You can use plugins to load your resources
  'frozen/plugins/loadImage!https://raw.github.com/iceddev/frozen/master/examples/imageExample/images/background.png',
  'frozen/plugins/loadImage!https://raw.github.com/iceddev/frozen/master/examples/imageExample/images/nyan.png'
], function(GameCore, keys, backImg, nyan){

  var x = 100;
  var y = 100;
  var speed = 3.5;

  //setup a GameCore instance
  var game = new GameCore({
    canvasId: 'canvas',
    gameAreaId: 'gameArea',
    canvasPercentage: 0.95, //95% of game area
    initInput: function(im){ //im = this.inputManager
      //tells the input manager to listen for key events
      im.addKeyAction(keys.LEFT_ARROW);
      im.addKeyAction(keys.RIGHT_ARROW);
      im.addKeyAction(keys.UP_ARROW);
      im.addKeyAction(keys.DOWN_ARROW);
    },
    handleInput: function(im){
      if(im.keyActions[keys.LEFT_ARROW].isPressed()){
        x-= speed;
      }
      if(im.keyActions[keys.RIGHT_ARROW].isPressed()){
        x+= speed;
      }
      if(im.keyActions[keys.UP_ARROW].isPressed()){
        y-= speed;
      }
      if(im.keyActions[keys.DOWN_ARROW].isPressed()){
        y+= speed;
      }
      
      //support touch events and mouse events
      if(im.mouseAction.isPressed()){
          x = im.mouseAction.position.x;
          y = im.mouseAction.position.y;
      }
    },
    update: function(millis){
      //no real game state to update in this example
    },
    draw: function(context){
      context.drawImage(backImg, 0, 0, this.width, this.height);
      //lets center the cat right under the mouse/touch point
      context.drawImage(nyan, x - nyan.width/2, y - nyan.height/2); 
    }
  });

  //if you want to take a look at the game object in dev tools
  console.log(game);

  //launch the game!
  game.run();
});