var juego = (function(){ var timer, velocidad = 20, canvas, contexto, presionada, cuadrado = { x: 100, y: 25, width: 50, height: 150 }; function actualizar() { 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() { contexto.clearRect(0, 0, canvas.width, canvas.height); //fillRect(x,y,width,height); contexto.fillRect(cuadrado.x, cuadrado.y, cuadrado.width, cuadrado.height); } function loop(){ actualizar(); dibujar(); timer = setTimeout(loop, velocidad); } function iniciarCanvas() { canvas = document.getElementById('canvas'); if (canvas.getContext){ contexto = canvas.getContext('2d'); } else throw "canvas no soportado!"; } function agregarManejador() { document.addEventListener('keydown', function(evento) { presionada = evento.keyCode; }); document.addEventListener('keyup', function(evento) { presionada = null; }); } return { iniciar: function() { iniciarCanvas(); agregarManejador(); loop(); }, detener: function() { clearTimeout(timer); } } })(); juego.iniciar();
<canvas id="canvas" width="600px" height="200px" style="border: solid 1px"> Tu explorador no soporta Canvas </canvas>