oCanvas has a middle layer for keyboard events. Normally you would just need to add events to the canvas, not specific display objects, so currently that's the only way keyboard events work with oCanvas.

That said, this middle layer still has some advantages. The biggest is that you can use the normal bind() method of the core instance, like with mouse and touch events. It also fixes some issues with keypress/keydown, fixes the event object and gives access to some useful helpers.

You can also specify which keys that should have its default action prevented. This can be useful for example in games, where you might want to use the space key without it causing the page to scroll.

Event Types

Gets triggered when the key is initially pressed down. Does not trigger while it is kept down.
Gets triggered when the key is pressed down and is continuously triggered until the key is released.
Gets triggered when the key is released.

Event Object

An event object is passed to the handler function as the first argument. This object contains most of the standard properties for a normal event object. Some things are changed though. The timeStamp property is not always correct in the normal object, so that is fixed and should be correct. The which property (used for checking which key was pressed) is fixed and contains what keyCode contains, if which is not correct.

If you really need the original event object, it is saved in the property originalEvent.

Keyboard Module

To bind handlers to keyboard events, you don't need to interact with the actual keyboard module of oCanvas — you just use the bind() method of the core instance. The keyboard module offers some extras though. These are described under Methods and Properties and exist on the keyboard module of the core instance. To make your code more clear, you can for example use core.keyboard.SPACE instead of just the number 32.



Keycode for the down arrow; 40
Keycode for the left arrow; 37
Keycode for the right arrow; 39
ARROW_UP : Number
Keycode for the up arrow; 38
ENTER : Number
Keycode for the enter key; 13
ESC : Number
Keycode for the escape key; 27
SPACE : Number
Keycode for the space key; 32


Example 1

This example shows how to add a handler to a keyboard event. Click in the output box and press down a key.

View Example
var canvas = oCanvas.create({
	canvas: "#canvas",
	background: "#ccc"

canvas.bind("keydown", function () {
	canvas.background.set("hsl(" + Math.random() * 360 + ", 50%, 50%)");