Canvas Arrow Keys Move Tile
HTML
<canvas id="c" width="500" height="500"></canvas>
<div id="coords">Use arrow keys to move</div>
CSS
body { padding:50px }
#c { border:1px solid grey; _border-radius:10px; margin-bottom:30px; }
JavaScript
var canvas = document.getElementById('c');
var ctx = canvas.getContext("2d");
var tile_size = 10;
var startX = canvas.width / 2;
var startY = canvas.height / 2;
// current x, y
var cx = startX,
cy = startY;
ctx.fillRect(startX, startY, tile_size, tile_size);
$(document).bind("keydown", function(e){
switch(e.keyCode)
{
//left
case 37:
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(cx - tile_size, cy, tile_size, tile_size);
cx -= tile_size;
break;
//up
case 38:
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(cx, cy - tile_size, tile_size, tile_size);
cy -= tile_size;
break;
//right
case 39:
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(cx + tile_size, cy, tile_size, tile_size);
cx += tile_size;
break;
//down
case 40:
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(cx, cy + tile_size, tile_size, tile_size);
cy += tile_size;
break;
}
$("#coords").text("cx: " + cx + ", cy: " + cy);
});