I've got a canvas and an onkeydown
event assigned to it. When any key is pressed, the console is supposed to log the keyCode of the key. But it's not outputting anything, not even undefined
. Other handlers like onclick
are working fine, but onkeydown
is not. I've also tried using onkeypress
and onkeyup
, but these don't work either. Here's the full code:
canvas.onkeydown = function(e){
if(e.keyCode === 37){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(knife,knifeX - 10, knifeY);
knifeX -= 10;
}
else if(e.keyCode === 39){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(knife,knifeX + 10, knifeY);
knifeX += 10;
}
else if(e.keyCode === 38){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(knife,knifeX, knifeY + 10);
knifeY += 10;
}
else if(e.keyCode === 40){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(knife,knifeX, knifeY - 10);
knifeY -= 10;
}
console.log(e.keyCode);
}
Instead of using canvas.onkeydown
, use window.onkeydown
, otherwise you will need to focus the canvas in order for it to work.
window.onkeydown = function() {};
Attaching event listeners to the canvas element will only work if you're focused* in on that element. The window object is the whole browser.
* The <canvas>
element requires the tabindex
attribute in order to be able to receive focus.