I am trying to make an already drawn square move with the WASD keys.
I wasn\'t sure how to do this, so I looked up some code, and after about 2 hours came up with my
Listen for keyboard events on the document, not the context.
document.addEventListener("keydown",move,false);
Here's some annotated code to get your started again:
// create canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// set canvas to be a tab stop (necessary to give it focus)
canvas.setAttribute('tabindex','0');
// set focus to the canvas
canvas.focus();
// create an x & y indicating where to draw the rect
var x=150;
var y=150;
// draw the rect for the first time
draw();
// listen for keydown events on the document
// the canvas does not trigger key events
document.addEventListener("keydown",handleKeydown,false);
// handle key events
function handleKeydown(e){
// if the canvas isn't focused,
// let some other element handle this key event
if(e.target.id!=='canvas'){return;}
// change x,y based on which key was down
switch(e.keyCode){
case 87: x+=20; break; // W
case 65: x-=20; break; // A
case 83: y+=20; break; // S
case 68: y-=20; break; // D
}
// redraw the canvas
draw();
}
// clear the canvas and redraw the rect in its new x,y position
function draw(){
ctx.clearRect(0,0,cw,ch);
ctx.fillRect(x,y,20,20);
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<h4>Click in the canvas to have it respond to keys</h4>
<canvas id="canvas" width=300 height=300></canvas>
The reason the square doesn't draw anymore is you are trying to attach an event listener to a canvas context, and you can only attach listeners to the DOM object (the canvas). So if you change the statements to (for example):
var canvas = document.getElementById('my_canvas');
canvas.addEventListener("keydown", move, true);
And leave the ctx statements as they are the canvas will draw again. Unless you really need a canvas you might be better off using an svg img.