Skip to content

Instantly share code, notes, and snippets.

@PaulKinlan
Created November 28, 2012 11:46
Show Gist options
  • Save PaulKinlan/4160675 to your computer and use it in GitHub Desktop.
Save PaulKinlan/4160675 to your computer and use it in GitHub Desktop.
Encapsulating Request Animation Frame
/*
Javascript is a funny thing.
Here are two things that will hit you with requestAnimationFrame
1) If you alias the window.requestAnimationFrame function on to anything other
than a window object, you get an Illegal Invocation Error.
You can solve this by using call() with the window object set.
2) Your callback will be called with the this method set to the window object.
You can solve this by calling bind() on your callback function with your game class.
*/
var Game = function(win) {
this.requestAnimationFrame = (function(w) {
return w.requestAnimationFrame ||
w.webkitRequestAnimationFrame ||
w.mozRequestAnimationFrame ||
w.oRequestAnimationFrame ||
w.msRequestAnimationFrame ||
function(callback) {
w.setTimeout(callback, 1000 / 60);
};
})(win).bind(win);
this.update_ = this.update.bind(this);
this.requestAnimationFrame(this.update_);
};
Game.prototype.update = function() {
// Do the game logic.
console.log("Update");
this.requestAnimationFrame(this.update_);
};
var g = new Game(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment