6.2 - KeyboardController

One of the simplest controls is the KeyboardControl. It also is easy to setup. We'll use the pheromone example, adding keyboard controls


The input to the Keyboard control is an array of objects, each with a key and cmd value. It looks like:

const keyCommands = [
    { key: 't', cmd: () => anim.toggle() },
    { key: 'o', cmd: () => anim.once() },
    { key: 'd', cmd: () => view.downloadCanvas() },
const keyboard = new Keyboard(keyCommands).start()

In this case, we have three keyboard actions:

The t key will toggle the animator .. i.e. if stopped, it'll start, otherwise it'll stop.

The o key will call the animator "once" function.

The d key will download the view's image.


You can create a character by a modifier key, primarily Shift and Alt/Option.

For alphabetic keys, Shift simply is the upper case of the key. Thus Shift-a is simply A. For non-alphabetic keys, like Shift-4, the key value is shown on the keyboard, in this case $.

The Alt/Option key differs in that it gives Unicode characters. For example:

Alt-a is å, and Alt-Shift-a, or Alt-A, is Å.

To use these. simply type them in an editor, terminal, or browser developer tools area to discover the character they correspond to.


Here are several more examples:

const keyCommands = [
    // These use the default modifier key, in this case the 'alt' key
    { key: 'q', cmd: () => console.log('q') },
    { key: '2', cmd: () => console.log('2') },
    { key: 'F2', cmd: () => console.log('F2') },
    { key: 'ArrowDown', cmd: () => console.log('ArrowDown') },
    { key: 'Escape', cmd: () => console.log('Escape') },
    { key: 'å', cmd: () => console.log('Alt-a') },
    { key: 'Å', cmd: () => console.log('Alt-Shift-a') },
    { key: '$', cmd: () => console.log('Shift-4') },
const keyboard = new Keyboard(keyCommands).start()

Finally, there are two methods to start/stop the keyboard.

  • keyboard.start()
  • keyboard.stop()


Here's a demo with several keyboard commands: mvc/helloKeys.html. The key commands are shown to the right of the model.