The model() function in p5.js allows you to render 3D geometry objects onto the canvas. It requires a p5.Geometry object as its argument, which describes the model's vertices, faces, and colors.
Prerequisites
- A WebGL canvas created with
createCanvas(w, h, WEBGL). - A valid
p5.Geometryobject, either built manually or loaded from an external file.
Building Geometry with buildGeometry()
You can create a custom p5.Geometry by passing a drawing function to buildGeometry(). Inside that function, you place standard p5.js shape calls like cone(), box(), or sphere(). The library captures those as a 3D model.
let model3D;
function setup() {
createCanvas(400, 400, WEBGL);
model3D = buildGeometry(() => {
cone(50, 100); // radius 50, height 100
});
}
function draw() {
background(200);
model(model3D);
}
Enabling Mouse Interaction
Use orbitControl() inside draw() to allow the user to rotate the view freely:
function draw() {
background(200);
orbitControl();
model(model3D);
}
This adds intuitive 3D exploration without extra code.
Full Example
let myShape;
function setup() {
createCanvas(400, 400, WEBGL);
myShape = buildGeometry(drawCone);
}
function drawCone() {
cone(50, 100);
}
function draw() {
background(200);
orbitControl();
model(myShape);
}
For more complex models, you can load .obj files with loadModel() and then pass them to model(). This approach works with exported geometry from 3D modeling software like Blender.
The model() function is the gateway to displaying any 3D geometry in p5.js, making it essential for interactive graphics, data visualization, and game prototypes.