Kontra​.keys

A minimalistic keyboard API. You can use it move the main sprite or respond to a key press.

function update() {
  if (kontra.keys.pressed('left')) {
    // move left
  }
}

Table of Contents

Available keys

Below is a list of keys that are provided by default. If you need to extend this list, you can use the kontra.keys.map property.

  • a-z
  • 0-9
  • enter, esc, space, left, up, right, down

kontra.keys​.bind(key)

key {string | string[]}
Keys to bind.
callback {function}
Function to call when the key is pressed.

Bind a set of keys to a function when pressed. Takes a single key or an array of keys. Passes the original event as a parameter.

kontra.keys.bind('p', function() {
  // pause the game
});
kontra.keys.bind(['enter', 'space'], function(e) {
  e.preventDefault();
  // fire gun
});

kontra.keys​.map

{object}

A map of keycodes to key names used in biding and unbinding. Add to this object to expand the list of available keys.

kontra.keys.map[34] = 'pageDown';

kontra.keys.bind('pageDown', function(e) {
  // handle pageDown key
});

kontra.keys​.pressed(key)

key {string}
Key name.

Returns true if the key is pressed. Use during an update() function to perform actions each frame.

kontra.sprite({
  update: function() {
    if (kontra.keys.pressed('left')){
      // left arrow pressed
    }
    else if (kontra.keys.pressed('right')) {
      // right arrow pressed
    }

    if (kontra.keys.pressed('up')) {
      // up arrow pressed
    }
    else if (kontra.keys.pressed('down')) {
      // down arrow pressed
    }
  }
});

kontra.keys​.unbind(key)

key {string | string[]}
Keys to unbind.

Unbind a bound set of keys. The bound function will no longer be called when the keys are pressed. Takes a single key or an array of keys.

kontra.keys.unbind('left');
kontra.keys.unbind(['enter', 'space']);