Keyboard
A minimalistic keyboard API. You can use it move the main sprite or respond to a key press.
import { initKeys, keyPressed } from 'kontra';
// this function must be called first before keyboard
// functions will work
initKeys();
function update() {
if (keyPressed('left')) {
// move left
}
}
Table of Contents
-
Properties
-
Methods
Available Keys
Below is a list of keys that are provided by default. If you need to extend this list, you can use the keyMap property.
- a-z
- 0-9
- enter, esc, space, left, up, right, down
bindKeys(keys)
Bind a set of keys that will call the callback function when they are pressed. Takes a single key or an array of keys. Is passed the original KeyboardEvent as a parameter.
import { initKeys, bindKeys } from 'kontra';
initKeys();
bindKeys('p', function(e) {
// pause the game
});
bindKeys(['enter', 'space'], function(e) {
e.preventDefault();
// fire gun
});
bindKeys Parameters
-
keys String or an Array of Strings. Key or keys to bind.
initKeys()
Initialize keyboard event listeners. This function must be called before using other keyboard functions.
keyMap
A map of keycodes to key names. Add to this object to expand the list of available keys.
import { keyMap, bindKeys } from 'kontra';
keyMap[34] = 'pageDown';
bindKeys('pageDown', function(e) {
// handle pageDown key
});
keyPressed(key)
Check if a key is currently pressed. Use during an update() function to perform actions each frame.
import { Sprite, initKeys, keyPressed } from 'kontra';
initKeys();
let sprite = Sprite({
update: function() {
if (keyPressed('left')){
// left arrow pressed
}
else if (keyPressed('right')) {
// right arrow pressed
}
if (keyPressed('up')) {
// up arrow pressed
}
else if (keyPressed('down')) {
// down arrow pressed
}
}
});
keyPressed Parameters
-
key String. Key to check for pressed state.
keyPressed Return value
true if the key is pressed, false otherwise.
unbindKeys(keys)
Remove the callback function for a bound set of keys. Takes a single key or an array of keys.
import { unbindKeys } from 'kontra';
unbindKeys('left');
unbindKeys(['enter', 'space']);
unbindKeys Parameters
-
keys String or an Array of Strings. Key or keys to unbind.