Interaction Design WikiProgramming

p5.js WebGL

In p5.js, there are two render modes: P2D (default renderer) and WEBGL. Both render modes utilize the html canvas element, however by enabling the WEBGL "context" on the canvas, we can now draw in both 2D and 3D. To enable WEBGL, simply specify as the third parameter in the createCanvas() function. In WEBGL mode we introduce a third dimension: Z that points toward you from the screen.

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
}

function draw(){
  background(255);
  box();
}

In WEBGL mode, there are currently 3 camera functions. The default camera view in WEBGL mode is perspective with a 60 degree field of view.

camera(x,y,z)
perspective(fovy, aspect, near, far)
ortho(left, right, bottom, top, near, far)

There are 7 different 3D geometry primitives in p5.js.

box()
plane()
sphere()
ellipsoid()
cone()
cylinder()
torus() 

The difference between drawing primitives in 2D and 3D is that 3D primitives take size parameters, but not position. To reposition 3D primitives, simply call:

translate(x,y,z)

Another way of drawing custom shapes in WEBGL mode is to use beginShape() and endShape(). This works exactly the same in 2D mode as it does in WEBGL, except in WEBGL, vertices receive x, y, and z as location coordinates.

beginShape();
vertex(100,23,-100);
vertex(200,23,-50);
vertex(150, 45,-100);
endShape();