StackOverflow_16919601: HTML5 Canvas camera/viewport - how to actually do it?
Illustration of the answer to: http://stackoverflow.com/q/16919601/2252829.
Move the player in a large map with nice viewport handler.
HTML
<!-- Arrow keys moves the player(black rectangle)-->
<canvas id="gameCanvas" width=400 height=400 />
JavaScript
/*
Updated answer in response to Honey Badger at "http://stackoverflow.com/a/16926273/2252829"
Using requestAnimationFrame instead of setInterval:
The most noted differences are the addition of requestAnimationFrame polyfill and the call of requestAnimationFrame at gameLoop function.
The differences between codes will be recognized by "<--" flag in comments
*/
// requestAnimationFrame polyfill
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
(function(){
var lastTime = 0;
var currTime, timeToCall, id;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
{
window.requestAnimationFrame = function(callback, element) {
currTime = Date.now();
timeToCall = Math.max(0, 16 - (currTime - lastTime));
id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame)
{
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
})(); // <-- added
// wrapper for our game "classes", "methods" and "objects"
window.Game = {};
// wrapper for "class" Rectangle
(function(){
function Rectangle(left, top, width, height){
this.left = left || 0;
this.top = top || 0;
this.width = width || 0;
this.height = height || 0;
this.right = this.left + this.width;
this.bottom = this.top + this.height;
}
Rectangle.prototype.set = function(left, top, /*optional*/width, /*optional*/height){
this.left = left;
this.top = top;
this.width = width || this.width;
...