JSFiddle - React, Tailwind, and code Playground
by pjnovas
HTML
<canvas id="canvas" width="600px" height="200px" style="border: solid 1px">
Tu explorador no soporta Canvas
</canvas>
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);
};
}());
/* Game Loop */
var juego = (function(){
var reqAnimId,
canvas,
contexto,
canvasBuffer,
contextoBuffer,
presionada,
cuadrado = {
x: 100,
y: 25,
width: 50,
height: 150
};
function actualizar() {
//actualizaciones del estado
switch(presionada){
case 37: //izquierda
cuadrado.x -= 10;
if (cuadrado.x < 0) cuadrado.x = 0;
break;
case 39: //derecha
cuadrado.x += 10;
if (cuadrado.x + cuadrado.width > canvas.width) cuadrado.x = canvas.width - cuadrado.width;
break;
}
}
function dibujar() {
contextoBuffer.clearRect(0, 0, canvas.width, canvas.height);
//dibujos en el contextoBuffer
contextoBuffer.fillRect(cuadrado.x, cuadrado.y, cuadrado.width, cuadrado.height);
contexto.clearRect(0, 0, canvas.width, canvas.height);
contexto.drawImage(canvasBuffer, 0, 0);
}
...