javascript - html5 canvas. document.onkeypress arrow keys not working -


i trying create simple html5 canvas football game. game has 3 options, player chooses left, right or centre kick ball, goal keeper random , dive left, right or stay in centre. want user press left, right or arrow keys trigger player kick ball can't code recognise when arrow keys pressed. have tried different keys work ie, return key.

function canvasapp(){             var canvas = document.getelementbyid("canvas");         var ctx = canvas.getcontext("2d");         //other var's          document.onkeypress = function dokeydown( e ) {             var key = e.keycode;             if ( key == 37  ){                 userchoice = key;             } else if (key == 38){                 userchoice = key;             } else if (key == 39){                 userchoice = key;             }         }          function draw() {             ctx.clearrect( 0, 0, canvas.width, canvas.height );                          //------------------------------------------------             //player shoots left             if ( userchoice == 37 ){                 //more code             //------------------------------------------------             //player shoots right             } else if ( userchoice == 39 ){                 //more code             //------------------------------------------------             //player shoots centre             } else if ( userchoice == 38 ) {                 //more code             }              //------------------------------------------------         }          function gameloop(){             window.settimeout(gameloop, framerate);             draw()         }         gameloop();     }      document.onclick = function( e ){         window.cleartimeout();     } 

if need see full code let me know , i'll put link jsfiddle.

you're triggering wrong event: use keydown instead: check page: http://help.dottoro.com/ljlkwans.php

the following snippet jquery: if use keypress event not work.

<html>     <head>         <title></title>         <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>     </head>     <body>     </body>     <script type="text/javascript">     $(document).ready(function(){          $(document).keydown(function(e){             var key = e.keycode;             if ( key == 37  ){                 console.log("left");             } else if (key == 38){                 console.log("center");             } else if (key == 39){                 console.log("right");             }         });     });     </script> </html> 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -