HTML5 Canvas Key Events

Anton Lytvynov
2 min readApr 27, 2021

--

How to handle key on your Canvas?

It’s pretty simply to listen to your keys; you listen to the event with the name ‘keydown’ and than you just need to find the right key code.

Html

<html lang="en">
<head>
<title>Canvas Keys</title>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet">
</head>

<body>
<canvas id="c" width="800" height="600">
This is a message for old browsers
</canvas>

<script src="script.js"></script>
</body>
</html>

Style.css

#c {
border: 1px solid;
display: block;
width: 800px;
height: 600px;
margin: 0 auto;
}

JavaScript & Keydown

window.onload = function () {
let canvas = document.getElementById('c');
let context = canvas.getContext("2d");

window.addEventListener('keydown', function (event) {
console.log(event);
});
}

So when you click any button you should see in your console log

Canvas keydown logs

And in this way we can see the key and its code

console.log('Key : ' + event.key + ' KeyCode: ' + event.keyCode);

Let’s handle just a few of keys : left, right, up, bottom

let KEY_CODE = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
};

window.addEventListener('keydown', function (event) {
switch (event.keyCode) {
case KEY_CODE.LEFT:
console.log('Left');
break;
case KEY_CODE.RIGHT:
console.log('Right');
break;
case KEY_CODE.DOWN:
console.log('Down');
break;
case KEY_CODE.UP:
console.log('Up');
break;
default:
break;
}
});

Now when we click on any button except of arrows we see nothing

Only arrow keys

Result

You can check the code for this part here.

Thank you for your attention.

Thank you for your attention.

Do you need help with web or mobile development? Feel free to contact me here.

P.S. I really appreciate your like or share 🙏.

--

--

Anton Lytvynov

CEO & Founder of Lytvynov Production, Senior web developer, architect, cryptocurrencies trader, https://lytvynov-production.com