0
# Event Handling & Input
1
2
Complete event system for mouse, keyboard, touch, and device motion interactions with both event callback functions and real-time input polling for responsive interactive applications.
3
4
## Capabilities
5
6
### Mouse Events and Variables
7
8
Mouse interaction handling with position tracking and button state management.
9
10
```javascript { .api }
11
/**
12
* Current mouse X coordinate relative to canvas
13
* @type {number}
14
*/
15
var mouseX;
16
17
/**
18
* Current mouse Y coordinate relative to canvas
19
* @type {number}
20
*/
21
var mouseY;
22
23
/**
24
* Previous mouse X coordinate from last frame
25
* @type {number}
26
*/
27
var pmouseX;
28
29
/**
30
* Previous mouse Y coordinate from last frame
31
* @type {number}
32
*/
33
var pmouseY;
34
35
/**
36
* Mouse X coordinate relative to browser window
37
* @type {number}
38
*/
39
var winMouseX;
40
41
/**
42
* Mouse Y coordinate relative to browser window
43
* @type {number}
44
*/
45
var winMouseY;
46
47
/**
48
* Previous window mouse X coordinate
49
* @type {number}
50
*/
51
var pwinMouseX;
52
53
/**
54
* Previous window mouse Y coordinate
55
* @type {number}
56
*/
57
var pwinMouseY;
58
59
/**
60
* Currently pressed mouse button (LEFT, RIGHT, CENTER)
61
* @type {string}
62
*/
63
var mouseButton;
64
65
/**
66
* Whether any mouse button is currently pressed
67
* @type {boolean}
68
*/
69
var mouseIsPressed;
70
71
/**
72
* Called when a mouse button is pressed
73
* Override this function to handle mouse press events
74
* @param {MouseEvent} [event] - Mouse event object
75
*/
76
function mousePressed(event) {}
77
78
/**
79
* Called when a mouse button is released
80
* Override this function to handle mouse release events
81
* @param {MouseEvent} [event] - Mouse event object
82
*/
83
function mouseReleased(event) {}
84
85
/**
86
* Called when mouse moves with no buttons pressed
87
* Override this function to handle mouse movement
88
* @param {MouseEvent} [event] - Mouse event object
89
*/
90
function mouseMoved(event) {}
91
92
/**
93
* Called when mouse moves with button pressed (dragging)
94
* Override this function to handle mouse dragging
95
* @param {MouseEvent} [event] - Mouse event object
96
*/
97
function mouseDragged(event) {}
98
99
/**
100
* Called when mouse is clicked (press and release)
101
* Override this function to handle mouse clicks
102
* @param {MouseEvent} [event] - Mouse event object
103
*/
104
function mouseClicked(event) {}
105
106
/**
107
* Called when mouse is double-clicked
108
* Override this function to handle double-clicks
109
* @param {MouseEvent} [event] - Mouse event object
110
*/
111
function doubleClicked(event) {}
112
113
/**
114
* Called when mouse wheel is scrolled
115
* Override this function to handle scroll events
116
* @param {WheelEvent} event - Wheel event object with delta information
117
*/
118
function mouseWheel(event) {}
119
```
120
121
### Keyboard Events and Variables
122
123
Keyboard input handling with key state tracking and event callbacks.
124
125
```javascript { .api }
126
/**
127
* Most recently pressed key as a string
128
* Special keys return descriptive names (e.g., 'ArrowUp')
129
* @type {string}
130
*/
131
var key;
132
133
/**
134
* Numeric code of the most recently pressed key
135
* @type {number}
136
*/
137
var keyCode;
138
139
/**
140
* Whether any key is currently pressed
141
* @type {boolean}
142
*/
143
var keyIsPressed;
144
145
/**
146
* Check if a specific key is currently being held down
147
* @param {number} code - Key code to check
148
* @returns {boolean} True if key is currently pressed
149
*/
150
function keyIsDown(code);
151
152
/**
153
* Called when a key is pressed down
154
* Override this function to handle key press events
155
* @param {KeyboardEvent} [event] - Keyboard event object
156
*/
157
function keyPressed(event) {}
158
159
/**
160
* Called when a key is released
161
* Override this function to handle key release events
162
* @param {KeyboardEvent} [event] - Keyboard event object
163
*/
164
function keyReleased(event) {}
165
166
/**
167
* Called when a key is typed (excludes special keys)
168
* Override this function to handle character input
169
* @param {KeyboardEvent} [event] - Keyboard event object
170
*/
171
function keyTyped(event) {}
172
```
173
174
### Touch Events and Variables
175
176
Multi-touch support for mobile and touch-enabled devices.
177
178
```javascript { .api }
179
/**
180
* Array of current touch points, each with x, y, and id properties
181
* @type {Touch[]}
182
*/
183
var touches;
184
185
/**
186
* Called when a touch begins
187
* Override this function to handle touch start events
188
* @param {TouchEvent} [event] - Touch event object
189
*/
190
function touchStarted(event) {}
191
192
/**
193
* Called when a touch point moves
194
* Override this function to handle touch movement
195
* @param {TouchEvent} [event] - Touch event object
196
*/
197
function touchMoved(event) {}
198
199
/**
200
* Called when a touch ends
201
* Override this function to handle touch end events
202
* @param {TouchEvent} [event] - Touch event object
203
*/
204
function touchEnded(event) {}
205
```
206
207
### Device Motion and Orientation
208
209
Device sensor input for mobile devices with accelerometer and gyroscope.
210
211
```javascript { .api }
212
/**
213
* Device acceleration along X-axis (excluding gravity)
214
* @type {number}
215
*/
216
var accelerationX;
217
218
/**
219
* Device acceleration along Y-axis (excluding gravity)
220
* @type {number}
221
*/
222
var accelerationY;
223
224
/**
225
* Device acceleration along Z-axis (excluding gravity)
226
* @type {number}
227
*/
228
var accelerationZ;
229
230
/**
231
* Previous frame's X acceleration
232
* @type {number}
233
*/
234
var pAccelerationX;
235
236
/**
237
* Previous frame's Y acceleration
238
* @type {number}
239
*/
240
var pAccelerationY;
241
242
/**
243
* Previous frame's Z acceleration
244
* @type {number}
245
*/
246
var pAccelerationZ;
247
248
/**
249
* Device rotation around X-axis (pitch)
250
* @type {number}
251
*/
252
var rotationX;
253
254
/**
255
* Device rotation around Y-axis (roll)
256
* @type {number}
257
*/
258
var rotationY;
259
260
/**
261
* Device rotation around Z-axis (yaw)
262
* @type {number}
263
*/
264
var rotationZ;
265
266
/**
267
* Previous frame's X rotation
268
* @type {number}
269
*/
270
var pRotationX;
271
272
/**
273
* Previous frame's Y rotation
274
* @type {number}
275
*/
276
var pRotationY;
277
278
/**
279
* Previous frame's Z rotation
280
* @type {number}
281
*/
282
var pRotationZ;
283
284
/**
285
* Called when device is moved
286
* Override this function to handle device motion
287
*/
288
function deviceMoved() {}
289
290
/**
291
* Called when device orientation changes
292
* Override this function to handle device rotation
293
*/
294
function deviceTurned() {}
295
296
/**
297
* Called when device is shaken
298
* Override this function to handle shake gestures
299
*/
300
function deviceShaken() {}
301
```
302
303
## Constants
304
305
```javascript { .api }
306
// Mouse button constants
307
const LEFT = 'left';
308
const RIGHT = 'right';
309
const CENTER = 'center';
310
311
// Key code constants for special keys
312
const BACKSPACE = 8;
313
const DELETE = 46;
314
const ENTER = 13;
315
const RETURN = 13;
316
const TAB = 9;
317
const ESCAPE = 27;
318
const SHIFT = 16;
319
const CONTROL = 17;
320
const OPTION = 18;
321
const ALT = 18;
322
const UP_ARROW = 38;
323
const DOWN_ARROW = 40;
324
const LEFT_ARROW = 37;
325
const RIGHT_ARROW = 39;
326
```
327
328
## Usage Examples
329
330
**Basic Mouse Interaction:**
331
```javascript
332
let circles = [];
333
334
function setup() {
335
createCanvas(400, 300);
336
}
337
338
function draw() {
339
background(220);
340
341
// Draw all circles
342
fill('blue');
343
for (let circle of circles) {
344
ellipse(circle.x, circle.y, circle.size);
345
}
346
347
// Show current mouse position
348
fill('red');
349
ellipse(mouseX, mouseY, 20);
350
351
// Show mouse trail
352
stroke('gray');
353
line(pmouseX, pmouseY, mouseX, mouseY);
354
}
355
356
function mousePressed() {
357
// Add circle where mouse was clicked
358
circles.push({
359
x: mouseX,
360
y: mouseY,
361
size: random(20, 60)
362
});
363
}
364
365
function doubleClicked() {
366
// Clear all circles on double-click
367
circles = [];
368
}
369
```
370
371
**Keyboard Input Handling:**
372
```javascript
373
let message = '';
374
let boxX = 200;
375
let boxY = 150;
376
377
function setup() {
378
createCanvas(400, 300);
379
}
380
381
function draw() {
382
background(220);
383
384
// Move box with arrow keys
385
if (keyIsPressed) {
386
if (keyCode === UP_ARROW) boxY -= 2;
387
if (keyCode === DOWN_ARROW) boxY += 2;
388
if (keyCode === LEFT_ARROW) boxX -= 2;
389
if (keyCode === RIGHT_ARROW) boxX += 2;
390
}
391
392
// Draw moveable box
393
fill('blue');
394
rect(boxX - 25, boxY - 25, 50, 50);
395
396
// Display typed message
397
fill('black');
398
textSize(16);
399
text('Type something: ' + message, 20, 30);
400
text('Use arrow keys to move box', 20, 50);
401
}
402
403
function keyPressed() {
404
if (keyCode === BACKSPACE) {
405
// Remove last character
406
message = message.substring(0, message.length - 1);
407
} else if (keyCode === ENTER) {
408
// Clear message on enter
409
message = '';
410
}
411
}
412
413
function keyTyped() {
414
// Add typed character to message
415
if (key !== BACKSPACE && key !== ENTER) {
416
message += key;
417
}
418
}
419
```
420
421
**Multi-touch Drawing:**
422
```javascript
423
let trails = {};
424
425
function setup() {
426
createCanvas(400, 300);
427
background(220);
428
}
429
430
function draw() {
431
// Fade background slightly
432
fill(220, 20);
433
noStroke();
434
rect(0, 0, width, height);
435
436
// Draw current touch points
437
for (let touch of touches) {
438
fill('red');
439
circle(touch.x, touch.y, 40);
440
441
// Draw trail for this touch
442
if (trails[touch.id]) {
443
stroke('blue');
444
strokeWeight(3);
445
let trail = trails[touch.id];
446
for (let i = 1; i < trail.length; i++) {
447
line(trail[i-1].x, trail[i-1].y, trail[i].x, trail[i].y);
448
}
449
}
450
}
451
}
452
453
function touchStarted() {
454
// Start a new trail for each touch
455
for (let touch of touches) {
456
trails[touch.id] = [{x: touch.x, y: touch.y}];
457
}
458
return false; // Prevent default
459
}
460
461
function touchMoved() {
462
// Add to trails
463
for (let touch of touches) {
464
if (trails[touch.id]) {
465
trails[touch.id].push({x: touch.x, y: touch.y});
466
// Limit trail length
467
if (trails[touch.id].length > 20) {
468
trails[touch.id].shift();
469
}
470
}
471
}
472
return false; // Prevent default
473
}
474
475
function touchEnded() {
476
// Clean up ended touches
477
let activeTouchIds = touches.map(t => t.id);
478
for (let id in trails) {
479
if (!activeTouchIds.includes(parseInt(id))) {
480
delete trails[id];
481
}
482
}
483
}
484
```
485
486
**Device Motion Visualization:**
487
```javascript
488
let history = [];
489
490
function setup() {
491
createCanvas(400, 300);
492
}
493
494
function draw() {
495
background(220);
496
497
// Add current acceleration to history
498
if (accelerationX !== undefined) {
499
history.push({
500
x: accelerationX,
501
y: accelerationY,
502
z: accelerationZ
503
});
504
505
// Limit history length
506
if (history.length > 100) {
507
history.shift();
508
}
509
}
510
511
// Draw acceleration history as lines
512
if (history.length > 1) {
513
stroke('red');
514
strokeWeight(2);
515
for (let i = 1; i < history.length; i++) {
516
let x1 = map(i - 1, 0, history.length - 1, 50, width - 50);
517
let y1 = map(history[i-1].x, -10, 10, height - 50, 50);
518
let x2 = map(i, 0, history.length - 1, 50, width - 50);
519
let y2 = map(history[i].x, -10, 10, height - 50, 50);
520
line(x1, y1, x2, y2);
521
}
522
523
stroke('green');
524
for (let i = 1; i < history.length; i++) {
525
let x1 = map(i - 1, 0, history.length - 1, 50, width - 50);
526
let y1 = map(history[i-1].y, -10, 10, height - 50, 50);
527
let x2 = map(i, 0, history.length - 1, 50, width - 50);
528
let y2 = map(history[i].y, -10, 10, height - 50, 50);
529
line(x1, y1, x2, y2);
530
}
531
532
stroke('blue');
533
for (let i = 1; i < history.length; i++) {
534
let x1 = map(i - 1, 0, history.length - 1, 50, width - 50);
535
let y1 = map(history[i-1].z, -10, 10, height - 50, 50);
536
let x2 = map(i, 0, history.length - 1, 50, width - 50);
537
let y2 = map(history[i].z, -10, 10, height - 50, 50);
538
line(x1, y1, x2, y2);
539
}
540
}
541
542
// Display current values
543
fill('black');
544
textSize(14);
545
text('Acceleration:', 20, 30);
546
text(`X: ${(accelerationX || 0).toFixed(2)}`, 20, 50);
547
text(`Y: ${(accelerationY || 0).toFixed(2)}`, 20, 70);
548
text(`Z: ${(accelerationZ || 0).toFixed(2)}`, 20, 90);
549
550
// Legend
551
fill('red');
552
text('X', 150, 50);
553
fill('green');
554
text('Y', 150, 70);
555
fill('blue');
556
text('Z', 150, 90);
557
}
558
559
function deviceShaken() {
560
// Clear history when device is shaken
561
history = [];
562
background(random(255), random(255), random(255));
563
}
564
```
565
566
**Advanced Mouse Interaction with States:**
567
```javascript
568
let mode = 'draw';
569
let shapes = [];
570
let currentShape = null;
571
572
function setup() {
573
createCanvas(400, 300);
574
}
575
576
function draw() {
577
background(220);
578
579
// Draw all completed shapes
580
for (let shape of shapes) {
581
drawShape(shape);
582
}
583
584
// Draw current shape being created
585
if (currentShape) {
586
drawShape(currentShape);
587
}
588
589
// Show mode
590
fill('black');
591
textSize(16);
592
text(`Mode: ${mode} (press 'd' for draw, 'e' for erase)`, 10, 20);
593
text(`Shapes: ${shapes.length}`, 10, 40);
594
}
595
596
function drawShape(shape) {
597
fill(shape.color);
598
noStroke();
599
for (let point of shape.points) {
600
circle(point.x, point.y, shape.size);
601
}
602
}
603
604
function mousePressed() {
605
if (mode === 'draw') {
606
currentShape = {
607
points: [{x: mouseX, y: mouseY}],
608
color: color(random(255), random(255), random(255), 150),
609
size: random(10, 30)
610
};
611
} else if (mode === 'erase') {
612
// Remove shapes near mouse
613
shapes = shapes.filter(shape => {
614
return !shape.points.some(point =>
615
dist(mouseX, mouseY, point.x, point.y) < 30
616
);
617
});
618
}
619
}
620
621
function mouseDragged() {
622
if (mode === 'draw' && currentShape) {
623
currentShape.points.push({x: mouseX, y: mouseY});
624
}
625
}
626
627
function mouseReleased() {
628
if (mode === 'draw' && currentShape) {
629
shapes.push(currentShape);
630
currentShape = null;
631
}
632
}
633
634
function keyPressed() {
635
if (key === 'd') mode = 'draw';
636
if (key === 'e') mode = 'erase';
637
if (key === 'c') shapes = []; // Clear all
638
}
639
```