I am working on a game-webpage, and I need to know of a way to capture keyboard input, ie up, down, left right and feed that into my location variable but I don't want to use a text box, in my HTML code for input. I'm already using a element to draw my world. Is there any way that when the game is open on a tab, that all keyboard input apart from and the various browser op开发者_如何学编程erator keys will will be capturable without having to have the user click on a specific spot on the screen. I've a very limited experience with HTML, and only need a cone of answer as I am building the game in python in a way that it builds itself into HTML.
I am also using a timed loop, and need to be able to have an onkeypress event to be capturable inside the timed loop.
Which element should I use? Which properties of the element?
In order to capture your presses specifically inside your loop, you'll have to store the currently held keys somewhere, and use the document.onkeydown
and document.onkeyup
to change them.
var heldKeys = [];
document.onkeydown = function(ev) {
heldKeys.push(ev.keyCode);
}
document.onkeyup = function(ev) {
var i = heldKeys.indexOf(ev.keyCode);
if (i != -1) {
heldKeys.splice(i, 1);
}
}
Now inside your loop, you check the contents of heldKeys
. You can just loop through it and act on each key.
Remember that the keyCodes won't correspond exactly to "a" "b" etc, they'll be ascii codes. And you may or may not run into browser compatibility issues.
精彩评论