Skip to content

Input

Input listens to keyboard and mouse events on a canvas element. Game creates one shared instance at services.input, so states can read input without adding their own event listeners.

Use a held check for continuous actions and a pressed check for one-off actions:

update(dt) {
const input = this.game.input;
if (input.isKeyHeld(Input.KEYS.ARROW_RIGHT)) {
this.x += 200 * dt;
}
if (input.isKeyPressed(Input.KEYS.ENTER)) {
this.confirm();
}
}
stateDiagram-v2
	[*] --> Up
	Up --> Held: keydown
	Held --> Up: keyup
	Held --> Consumed: isKeyPressed()
	Consumed --> Held: next keydown event
new Input(canvas);

Attaches keyboard and mouse listeners to an HTMLCanvasElement. The constructor calls its private listener setup automatically. The canvas must have focus to receive keyboard events; Game’s canvas is focusable and focuses itself when created.

A map of readable names to browser KeyboardEvent.key values. Prefer these constants over handwritten strings.

Input.KEYS.ENTER; // "Enter"
Input.KEYS.ARROW_LEFT; // "ArrowLeft"
Input.KEYS.SPACE; // " "

A map of mouse-button names to browser button numbers.

Input.MOUSE.LEFT; // 0
Input.MOUSE.MIDDLE; // 1
Input.MOUSE.RIGHT; // 2
input.isKeyHeld(Input.KEYS.ARROW_UP);

Returns true while the key is held. Use it for continuous movement or other actions that should repeat while input remains down.

if (input.isKeyPressed(Input.KEYS.ENTER)) {
openDialog();
}

Returns true once and consumes that recorded key press. A second call for the same key returns false until another keydown event occurs. Read a consumed action in one place so two systems do not compete for it.

const { x, y } = input.getMousePosition();

Returns a copy of the current pointer position in the canvas’s logical coordinate system. It accounts for CSS display size and the canvas rendering scale, so the result can be used directly for canvas hit testing.

input.isMouseButtonHeld(Input.MOUSE.LEFT);

Returns true while the selected mouse button is held. Use it for dragging.

if (input.isMouseButtonPressed(Input.MOUSE.LEFT)) {
selectAt(input.getMousePosition());
}

Returns true once and consumes the recorded press for that button.

if (input.isMouseButtonReleased(Input.MOUSE.LEFT)) {
finishDrag();
}

Returns true once and consumes the recorded release. Use it to complete a drag or click interaction.

mouse, keys, mouseButtons, mouseButtonPresses, and mouseButtonReleases expose the tracked values, but application code should use the methods above. The methods provide safer defaults, encapsulate coordinate conversion, and make consuming behavior explicit.