Loops and Interactivity
The sketch created in Exercise 01 was expanded to make it interactive. The variablesmouseX
, mouseY
, and key
and the function keyPressed()
, all
of which are included in the p5.js library, were used in this exercise to add some basic interactivity.
Mouse Interactivity
The mouse position can be used in a variety of ways to control the properties of elements on the canvas. To get the mouse
position, the mouseX
and mouseY
variables are used. These store the x and y coordinates of the cursor
relative to the origin (0, 0) of the canvas.
For instance, the size of a shape can be controlled by the position of the mouse on the canvas. In the code snippet below, the x and y coordinates of the mouse control the size of the tiles on the grid.
function draw() {
let stepX = mouseX + 1;
let stepY = mouseY + 1;
for (let gridX = 0; gridX < width; gridX += stepX) {
for (let gridY = 0; gridY < height; gridY += stepY) {
fill(gridX, height - gridY, 100);
rect(gridX, gridY, stepX, stepY);
}
}
}
Keyboard Interactivity
Keyboard inputs can also be used to apply interactivity to graphics created with p5.
In the code below, the keyPressed()
function runs when a specific key is pressed. The key that was pressed by
the user is stored in the key
variable. If the user presses S, whether it's in lowercase or uppercase,
the current canvas is saved as an image in PNG file format.
function keyPressed() {
if (key == 's' || key == 'S') {
saveCanvas(gd.timestamp(), 'png');
}
}