Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to create key events in HTML5 canvas?

Please suggest the best way to create key events for HTML5 canvas. I don't prefer any library, but if you think that it's the best way then go answer it. Thanks in advance!

like image 804
user1441816 Avatar asked Sep 03 '12 01:09

user1441816


People also ask

Is HTML5 canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.

Which built in HTML5 object is used to draw on the canvas?

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics.


2 Answers

If you want to set key event handling on the <canvas> itself (not the window or document), set a tabindex on the <canvas> element. Note that the canvas will need to be in focus on to catch key events.

<script>     document.getElementById('game').addEventListener('keypress', handleKeyPress);     function handleKeyPress(e) { ... } </script> <canvas id="game" tabindex="1" width="350" height="200"> </canvas> 

This is how it is done on the Processing.js website.

If you don't want a border to appear when you click on the canvas, set its style to outline: none.

like image 25
Brian Duncan Avatar answered Sep 19 '22 18:09

Brian Duncan


This will return the key code:

<canvas id="myCanvas" width="200" height="100" style="background:green"></canvas> <script type="text/javascript"> window.addEventListener('keydown',this.check,false);  function check(e) {     alert(e.keyCode); } </script> 

If you would like a demonstration of different things being done based on key:

function check(e) {     var code = e.keyCode;     //Up arrow pressed     if (code == 38)         alert("You pressed the Up arrow key");     else         alert("You pressed some other key I don't really care about."); } 

Or if you have a long list of keys you'll be using, do it in a switch case:

function check(e) {     var code = e.keyCode;     switch (code) {         case 37: alert("Left"); break; //Left key         case 38: alert("Up"); break; //Up key         case 39: alert("Right"); break; //Right key         case 40: alert("Down"); break; //Down key         default: alert(code); //Everything else     } } 
like image 146
Rhyono Avatar answered Sep 17 '22 18:09

Rhyono