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
redraw
redraw()
is a p5.js function which makes the code inside draw()
function to be executed only one time when necessary.
This function is used inside events.
Example
Here is an example code which makes the ellipse moving every time the user presses the mouse:
// create a variable to control the direction of the ellipse
let control = false;
// make ellipse starting from the left end of the canvas
let i=30;
function setup() {
// create canvas
createCanvas(800,500);
noLoop();
}
function draw () {
// set background color
background('#31bc33');
// when ellipse is in the left edge, control would be/become false
if (i==30) {
control = false;
}
ellipse(i,height/2,60);
}
function mousePressed() {
if (i<(width-30) && control==false){
i=i+20;
}
else {
// else control will change to true
control = true;
// decrease its x position (ellipse moves in the left direction)
i=i-20;
}
// use redraw to update the position of ellipse
redraw();
}
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 asex922.js
- Open the file
ex812.html
in your editor and save it asex922.html
- In the
ex922.html
file, update the link toex922.js
from exersice812.js - Go to the
index.html
file and create, underModule 9
, alink
to theex922.html
file with the title "redraw".
Modify the ex922.js
file to use redraw() to create an ellipse which will change its size every time the mouse is pressed. The size of the ellipse should not exceed the canvas height. When it reaches the maximum point it should start decreasing its size until it reaches 30 px. You can see here an example.
// create a variable to control the size of the ellipse
let control = false;
// make ellipse starting from the left end of the canvas
let i=30;
function setup() {
// create canvas
createCanvas(800,500);
noLoop();
}
function draw () {
// set background color
background('#31bc33');
// when ellipse is 30px change the control to false
if (i==30) {
control = false;
}
ellipse(width/2,height/2,i);
}
function mousePressed() {
// if the ellipse size do no exceed the canvas height
if (i<(height-30) && control ==false){
// increase the size of the ellipse
i=i+20;
}
else {
// else control will change to true
control = true;
// decrease the size of the ellipse
i=i-20;
}
// use redraw to update the size of ellipse
redraw();
}
Do a Git commit with the message "redraw".
- See more about the redraw() function