Submodule 16.2: Basics of p5.js
Submodule 16.2: Basics of p5.js
- setup() and draw() functions
- createCanvas
- Primitives Shapes
Motion
P5.js enables us to easily create movement/animation of objects.
Although this concept is new, the base is the good understanding of our canvas coordinates.
Now that you have created some shapes and you have become familiar with our canvas coordinates, its time to use your new knowledge together with JavaScript to create a simple animation. How would you create an ellipse moving horizontally from the left to the right end of your canvas and vice versa?
// 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);
// set background color
background('#31bc33');
}
function draw () {
// when ellipse is in the left edge, control would be/become false
if (i==30) {
control = false;
}
// if ellipse is inside the canvas width (we substract 30 which is the radius
// of our ellipse) and control is false
if (i<(width-30) && control==false){
i++
// increase its x position (ellipse moves in the right direction)
ellipse(i,height/2,60);
}
else {
// else control will change to true
control = true;
// decrease its x position (ellipse moves in the left direction)
i--;
ellipse(i,height/2,60);
}
}
You can see here an example.
You may have noticed that your ellipse is leaving traces as it is moving through the canvas. Why do you think this happens? What would you do if you wanted to change it?
Exercise
- Open your Visual Studio editor and the
p5yourName
folder. - Open the file
ex812.js
in your editor and save it asex828.js
- Open the file
ex812.html
in your editor and save it asex828.html
- In the
ex828.html
file, update the link toex828.js
from ex812.js - Go to the
index.html
file and create, underModule 8
, alink
to theex828.html
file with the title "Motion".
Modify the ex828.js
file in order to create a two-dimensional motion with collisions You can see here an example.
Do a Git commit with the message "Motion".