Input
The Input
class manages keyboard and mouse input for a game or application by registering event listeners on a given canvas
element. It provides methods to check for held and pressed keys, as well as mouse positions and button presses.
Static Properties
Input.KEYS
Input.KEYS;
A constant object mapping key names to their string representations. This includes common keyboard keys such as alphanumeric keys, special keys, and function keys.
Example:
Input.KEYS.ENTER; // "Enter"Input.KEYS.ARROW_LEFT; // "ArrowLeft"
Input.MOUSE
Input.MOUSE;
A constant object mapping mouse buttons to their numerical values.
LEFT
(0
)MIDDLE
(1
)RIGHT
(2
)
Example:
Input.MOUSE.LEFT; // 0Input.MOUSE.RIGHT; // 2
Constructor
new Input(canvas)
Initializes the Input
object, attaches event listeners for keyboard and mouse events to the provided canvas
element.
- Parameters:
canvas
(HTMLCanvasElement
): The canvas element to capture input events from.
Example:
const input = new Input(document.getElementById('gameCanvas'));
Methods
initEventListeners()
Sets up event listeners for keydown
, keyup
, mousemove
, mousedown
, and mouseup
events. Automatically called in the constructor.
- Returns:
void
isKeyHeld(key)
Checks if a key is currently being held down.
-
Parameters:
key
(String
): The key to check (case-insensitive).
-
Returns:
Boolean
:true
if the key is being held down,false
otherwise.
Example:
if (input.isKeyHeld(Input.KEYS.ARROW_UP)) { // Move player up}
isKeyPressed(key)
Checks if a key was pressed once (and resets the key state to prevent continuous firing).
-
Parameters:
key
(String
): The key to check (case-insensitive).
-
Returns:
Boolean
:true
if the key was pressed,false
otherwise.
Example:
if (input.isKeyPressed(Input.KEYS.ENTER)) { // Confirm selection}
getMousePosition()
Returns the current position of the mouse relative to the canvas.
- Returns:
Object
: An object withx
andy
properties representing the mouse’s position.
Example:
const mousePos = input.getMousePosition();console.log(`Mouse X: ${mousePos.x}, Mouse Y: ${mousePos.y}`);
isMouseButtonHeld(button)
Checks if a specific mouse button is currently being held down.
-
Parameters:
button
(Number
): The mouse button to check (e.g.,Input.MOUSE.LEFT
).
-
Returns:
Boolean
:true
if the button is being held down,false
otherwise.
Example:
if (input.isMouseButtonHeld(Input.MOUSE.LEFT)) { // Dragging logic}
isMouseButtonPressed(button)
Checks if a specific mouse button was pressed once (and resets the button state).
-
Parameters:
button
(Number
): The mouse button to check (e.g.,Input.MOUSE.LEFT
).
-
Returns:
Boolean
:true
if the button was pressed,false
otherwise.
Example:
if (input.isMouseButtonPressed(Input.MOUSE.LEFT)) { // Select tile}