This tutorial will show you how to move a square with your arrow keys in an HTML5 Canvas. I will have to define two functions for this to work. The drawbackground function will draw the blue background. An event listener will have to be setup to move the square with your arrow keys. The doKeydown function that is tied to the event listener will add or subtract the squares x and y coord, clear the square so it wont move like a snake, draw the background, and the x and y coords will be plugged into the char.fillRect function to be redrawn to another location. There are 2 loops that are setup in the function drawbackground(). One is for the x position and the other is for the y position. The coordinates will be fed into the cxt.fillRect function. The algorithm outputs the tiles from left to right and top to bottom.
<html>
<head>
<title>Move Square</title>
</head>
<body>
<canvas id=”myCanvas” width=”192″ height=”192″ />
<script type=”text/javascript”>
var c=document.getElementById(“myCanvas”);
var cxt=c.getContext(“2d”);
function drawbackground()
{
for (y=0;y<=5;y++){
for (x=0;x<=5;x++){
var randomnumber=0;
if(randomnumber==0)
{
cxt.fillStyle=”blue”;
}
else
{
cxt.fillStyle=”green”;
}
cxt.fillRect((x*32),(y*32),32,32);
}
}
char.fillStyle=”#FF0000″;
char.fillRect(charx,chary,32,32);
}
function doKeyDown(evt)
{
switch (evt.keyCode)
{
case 38: /* Up arrow was pressed */
{
chary=chary-1;
char.clearRect(0, 0, 32, 32);
drawbackground();
char.fillStyle=”black”;
char.fillRect(charx,chary,32,32);
}
break;
case 40: /* Down arrow was pressed */
{
chary=chary+1;
char.clearRect(0, 0, 32, 32);
drawbackground();
char.fillStyle = “black”;
char.fillRect(charx,chary,32,32);
}
break;
case 37: /* Left arrow was pressed */
{
charx=charx-1;
char.clearRect(0, 0, 32, 32);
drawbackground();
char.fillStyle=”black”;
char.fillRect(charx,chary,32,32);
}
break;
case 39: /* Right arrow was pressed */
{
charx=charx+1;
char.clearRect(0, 0, 32, 32);
drawbackground();
char.fillStyle=”black”;
char.fillRect(charx,chary,32,32);
}
break;
}
}
var charx=0;
var chary=0;
var c=document.getElementById(“myCanvas”);
var cxt=c.getContext(“2d”);
var char=c.getContext(“2d”);
window.addEventListener(‘keydown’,doKeyDown,true);
drawbackground();
char.fillStyle=”black”;
char.fillRect(charx,chary,32,32);
</script>
</body>
</html>