AnimacionSprites

by pjnovas

HTML

<canvas id="canvas" width="200px" height="200px">
  Tu explorador no soporta Canvas
</canvas>

<ul>
    <li>
        <label>1</label><label>2</label><label>3</label><label>4</label><span>Selecci&oacute;n</span>
    </li>
    <li>
        <label>A</label><span>Acci&oacute;n</span>
    </li>
    <li>
        <label>R</label><span>Recargar</span>
    </li>
</ul>

CSS

canvas {
    border: solid 1px gray;
    float: left;
    margin-right: 20px;
}

ul {
    list-style: none;
    padding: 0;
}

label {
    padding: 2px 8px;
    border: solid 1px silver;
    margin: 2px;
    background: rgb(245, 245, 245);
    display: inline-block;
}

span {
    font-weight: bold;
    margin-left: 5px;
}

JavaScript

//requestAnimationFrame polyfill de Erik Möller
//http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating"    
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelRequestAnimationFrame = window[vendors[x]+
          'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

/* Configuracion de Sprites */

var armas = ['cuchillo', 'pistola', 'escopeta', 'grosa'];
var sprites = {
    dimension: {
        ancho: 200,
        alto: 200
    },
    cuchillo: {
        libre: [0,0],
        accion: [[1,0],[2,0],[1,0]]
    },
    pistola: {
        libre: [0,2],
        accion: [[0,2],[1,2],[2,2],[3,2],[4,2],[5,2]],
        recarga: [[0,1],[1,1],[2,1],[3,1],[4,1],[0,1]]
    },
    escopeta: {
        libre: [0,3],
        accion: [[3,0],[4,0],[5,0]],
        recarga: [[1,3],[2,3],[3,3],[4,3],[5,3]]
    },
    grosa: {
        libre: [0,4],
        accion: [[1,4],[2,4],[3,4],[4,4],[5,4]]
    }
};

/* Game Loop */

var juego = (function(){
  var reqAnimId,
      canvas,
      contexto,
      canvasBuffer,
      contextoBuffer,
      arma = 'cuchillo',
      estado = 'libre',
      pos = {
          x: 0,
          y: 0
      },
      cambioArmaVel = 15,
      offsetY = 0,
      offsetMax = 5;
   ...