3D Camera Using WebGL in P5.js

Since I was curious about drawing 3D shapes, this time I explored how to do it in p5.js. Thank God that p5.js supports 3D shapes. In p5.js, to draw both 3D and 2D shapes, we use WebGL as a renderer. It’s interesting that when we use WebGL, the canvas environment is changed completely. Now, every time I use WebGL, I have to think of Z coordinate. It’s frustrating at first, since I’m still confused about how X, Y, and Z coordinates work.

To use WebGL as a renderer, just put this code in setup() function:


function setup() {
createCanvas(400, 400, WEBGL);
}

So, I had to sketch to figure out how exactly was X, Y, and Z coordinates. Here’s my sketches.

Me trying to figure out X, Y, and Z axises

I also learned that when using WebGL, the coordinate (0,0) is not on the top-left corner, but the coordinate, plus Z-coordinate, that’s (0,0,0) is exactly in the middle of canvas.

Thus, whenever I wanted to use translate to relocate the drawing, I needed to think of Z-coordinate which was very confusing (also, because there aren’t any grid on the canvas).

In order to get used to 3D object, first I tried to load a 3D object into the canvas. I used a teapot.obj as an example. Here, I could tell the difference how 2D and 3D objects work. In this example, I also used rotateX and rotate Y to know how the rotation on X and Y coordinates work.

To load a 3D object in p5.js, I used load function.


let teapot;

function setup() {
createCanvas(400, 400, WEBGL);
perspective();
teapot = loadModel('teapot.obj');
}

And just put it in the draw function like this.


function draw() {

model(teapot);

}

After pretty much I got a basic idea, then I started to draw a raw 3D shape using 3D primitive shapes in p5.js. I used box, cylinder, and cone. Here’s my 3D camera looks like.

3D Camera

Now that we learned how to organize code into functions, I also separated each shape functions and call them in draw function. I drew multiple pine trees with different size and coordinates using return function with arguments.

This is the example of how I broke the codes out of draw function.


function draw() {

let aquaLight = color(183, 217, 247);

// draw background
background(aquaLight);

// control orbit (click and drag)
orbitControl();

// draw the camera
drawCamera();

// draw light from camera
drawLight();

// draw pine
drawPine(0, -350, 30, 60, 10, 100);
}

Here’s my code. And here’s my final result.

Click and drag the mouse to see 3D world!

Leave a Reply

Your email address will not be published. Required fields are marked *