Book
Submodule 17.2: Advanced p5 functions and transformations
Submodule 17.2: Advanced p5 functions and transformations
Completion requirements
View
- noLoop and loop
- redraw
- clear
- translate and rotate
- random
clear
clear()
is a p5.js function which when called, clears everything that is inside the canvas.
This function does not actually delete the elements. It clears them by making them transparent.
Example
Here is an example code which clears the canvas every time the mouse is pressed :
function setup() {
createCanvas(windowWidth, windowHeight);
// set background color in the setup so sketches will leave traces
background('white');
}
function draw() {
noStroke();
fill(0, 0, 0, 30);
// ellipse will change according to the mouseX and mouseY position
ellipse(mouseX, mouseY, 30, 30);
}
// clear the canvas every time the user presses the mouse
function mousePressed() {
clear();
}
You can see the result of the above code here
Exercise
- Open your Visual Studio editor and the
p5yourName
folder. - Open the file
ex812.js
in your editor and save it asex923.js
- Open the file
ex812.html
in your editor and save it asex923.html
- In the
ex923.html
file, update the link toex923.js
from exersice812.js - Go to the
index.html
file and create, underModule 9
, alink
to theex923.html
file with the title "clear".
Modify the ex923.js
file to create a drawing program which will be draw ellipses in the mouseX and mouseY position every time the user presses the mouse. Clear the sketch every time the user presses a key using the information from here. You can see here an example.
function setup() {
createCanvas(windowWidth, windowHeight);
// set background color
background('white');
}
function draw() {
noStroke();
fill(0, 0, 0, 30);
if (mouseIsPressed) {
// ellipse will be drawn to the mouseX and mouseY position
ellipse(mouseX, mouseY, 30, 30);
}
}
// clear the canvas every time the user presses a key
function keyPressed() {
clear();
}
Do a Git commit with the message "clear".
- See more about the clear() function