Skip to content

Instantly share code, notes, and snippets.

@pjnovas
Created September 6, 2012 01:11
Show Gist options
  • Save pjnovas/3649399 to your computer and use it in GitHub Desktop.
Save pjnovas/3649399 to your computer and use it in GitHub Desktop.
Ejemplo de Game Loop para FernetJS: http://fernetjs.com/2012/09/game-loop-con-html5/
var juego = (function(){
  var reqAnimId,
    canvas,
    contexto,
canvasBuffer,
contextoBuffer;
 
  function actualizar() {
    //actualizaciones del estado
  }
 
  function dibujar() {
    contextoBuffer.clearRect(0, 0, canvas.width, canvas.height);
  
   //dibujos en el contextoBuffer
 
   contexto.clearRect(0, 0, canvas.width, canvas.height); 
   contexto.drawImage(canvasBuffer, 0, 0);
  }
 
  function iniciarCanvas() {
    canvas = document.getElementById('canvas');
     
    canvasBuffer = document.createElement('canvas');
    canvasBuffer.width = canvas.width;
    canvasBuffer.height = canvas.height;
     
    if (canvas.getContext){
      contexto = canvas.getContext('2d');
      contextoBuffer = canvasBuffer.getContext('2d');
    }
    else throw "canvas no soportado!";
  }
 
  function loop(){
   actualizar();
   dibujar();
 
   reqAnimId = window.requestAnimationFrame(loop);
  }
 
 return {
   iniciar: function() {
if (!canvas)
     iniciarCanvas();
  
   loop();
   },
   detener: function() {
     if (reqAnimId)
window.cancelAnimationFrame(requestAnimId);
requestAnimId = 0;
   }
 }
 
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment