Submodule 16.2: Basics of p5.js
Primitives Shapes - ellipse
Let's start drawing!
p5.js has pre-build primitives shapes functions which makes it easy to draw shapes in the canvas.
One of these is the ellipse();
This function has 4 basic parameters and thus accepts 4 arguments.
These arguments are: x position, y position, width and height which are expressed in the ellipse as : ellipse(x,y,w,h);
Thus, the first two values of an ellipse are its x and y coordinates. The canvas (0,0) coordinates are on the upper left corner. Thus x position increases in the right direction and y position as we go down the canvas. When we are at the upper right corner, x position is equal to the width of our canvas whereas when we are in the lowest point of the canvas, the y position equals with canvas height.
The two other values determine not only its width and height but also whether we will display an ellipse or a cycle. If the w,h have equal values, we create a cycle. The same result will happen if we only define the width since p5.js automatically assigns the same value for height.
Example 1
Here is an example code for an ellipse ( cycle) displayed in the center of the canvas:
function setup() {
// create canvas
createCanvas(800,500);
// set background color
background('#31bc33');
}
function draw () {
ellipse(width/2,height/2,60);
}
Exercise
- Open your Visual Studio editor and the
p5yourName
folder. - Open the file
ex812.js
in your editor and save it asex823.js
- Open the file
ex812.html
in your editor and save it asex823.html
- In the
ex823.html
file, update the link toex823.js
from exersice812.js - Go to the
index.html
file and create, underModule 8
, alink
to theex823.html
file with the title "Primitives Shapes - ellipse".
Modify the ex823.js
file to create a face. You can see here an example.
function setup() {
createCanvas(800, 600);
// set background color
background('#D66761');
}
function draw() {
noFill();
// create the face ellipse
ellipse(width/2,height/2,200,300)
// for the left eye
// draw the base ellipse for the eye, the sclera/“white of the eye”
ellipse(350,275,50,25);
// draw the Iris for the eye
ellipse(350,275,25);
// draw the center of the eye
fill('black');
ellipse(350,275,12.5);
// for the right eye
// draw the base ellipse for the eye, the sclera/“white of the eye”
noFill();
ellipse(450,275,50,25);
// draw the Iris for the eye
ellipse(450,275,25);
// draw the center of the eye
fill('black');
ellipse(450,275,12.5);
}
Do a Git commit with the message "Primitives Shapes - ellipse".