Kranker_Apfel Posted February 3, 2018 Share Posted February 3, 2018 Hello people ! I'm working on a project code in javascript without using any framework and I struggle with keyboard input. I would like to disable window (or document, I don't know the difference) keyboard detection while I'm in game, because the webpage move each time I use arrows keys to move my player. I already try to use getElementByID('myCanvas').onkeydown but it doesn't work at all ! Here a part of my code : /* In a class name Engine() */ document.onkeydown = checkKey; function checkKey(e) { var keysMap = { 37 : [-1,0], 38 : [0,-1], 39 : [1,0], 40 : [0,1], }; if(e.keyCode>=37 && e.keyCode<=40){ player.setSprite(player.spriteDict[e.keyCode]) game.moveTo(keysMap[e.keyCode][0],keysMap[e.keyCode][1]); } else if(e.keyCode == 82){ game.restart(); } else if (e.keyCode == 85){ game.undo(); } current.drawBoard(); } For more, see the project on Github https://github.com/KrankerApfel/Sokoban-Level-Generator Quote Link to comment Share on other sites More sharing options...
waechtertroll Posted February 5, 2018 Share Posted February 5, 2018 You might want to do the following: - Add `tabindex = 1` to your canvas element so it can be focused - Store the canvas DOM element in a variable (you might be doing this anyway to init the canvas...) - Attach a listener to window.onfocus. Due to event bubbling it should be called anytime focus inside your page changes. Make it do something in the spirit of `if (document.activeElement !== canvasDOMNode) canvasDOMNode.focus()` - On init, once call `canvasDOMNode.focus()` to be sure to start inside the game canvas This should assure all your input events go to the canvas first. Remember to make them .preventDefault() (and maybe .stopPropagation() ) so they keys won't bubble up and move the page. Be aware that this may break other input elements on the web page. I'm using a similar approach in a complex desktop-app like environment and it works well. If you feel like using existing modules, you might want to check out mousetrap which applies that technique in a very sophisticated way. Quote Link to comment Share on other sites More sharing options...
waechtertroll Posted February 5, 2018 Share Posted February 5, 2018 A bit of playing around showed that in your situation it should be better to just add `e.preventDefault()` to your keyboard handler; as this leaves the rest of the page intact (maybe your game is embedded in another webpage?). In the example the canvas is blue. Click it once to enter the game. Pressing up/down send a message to the console and no scrolling is triggered. Pressing left/right will leave a message on the console and still trigger scrolling. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.