requestAnimationFrame example
HTML
<canvas id="canvas" width=512 height=512>
JavaScript
//=========================================================================
// cross browser requestAnimationFrame/cancelAnimationFrame.
// http://paulirish.com/2011/requestanimationframe-for-smart-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.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback, element) {
var currTime = Date.now();
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);
};
}
})();
window.myAnimation = (function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var x = 0;
var y = canvas.height / 2;
var width = 50;
var height = 50;
var velocity = 0;
var toggle = false;
var time = 0;
function update() {
context.clearRect(x-1, y-1, width+2, height+2);
time = new Date().getTime() * 0.002;
x = Math.sin(time) * 192 + 256;
y = Math.cos(time * 0.9) * 192 + 256;
context.fllRect(x, y, width, height);
toggle = !toggle;
}
return {
update: update
}
})();
// encapsulate the Game in one object to avoid creation of unnecessary global...