On the 2D plain of a browser window p5.js can represent 3D space using WEBGL. This is specified as the third argument to the createCanvas() function in the setup portion of the sketch:
createCanvas(400, 300, WEBGL);
Here is some code that demonstrates how to rotate a 2D rectangle on the X axis, using rotateX(), which takes in an angle of radians as an argument.
let angle = 0;
function setup() {
createCanvas(400, 300, WEBGL);
}
function draw() {
background(175);
rectMode(CENTER);
fill(0,0,255);
rotateX(angle);
rect(0, 0, 150, 150);
angle += 0.025;
}
We can also use rotateY() to rotate it on the Y axis:
Or rotateZ() to rotate on the Z axis:
Or on all three axis at the same time:
Here is some code for rotating a 3D cube on all three axis. In p5.js, a cube is created with box().
let angle = 0;
function setup() {
createCanvas(400, 300, WEBGL);
}
function draw() {
background(175);
rotateX(angle);
rotateY(angle);
rotateZ(angle * 0.75);
// box(w, h, d)
// if only one arg, then use the value for all three dimensions
box(175);
angle += 0.025;
}
For more information see:
https://p5js.org/reference/#/p5/box
https://p5js.org/reference/#/p5/rotateX
https://p5js.org/examples/3d-geometries.html