The box() function is the simplest03 way to generate a 3D solid in p5.js. It produces a cuboid (or cube) with six rectangular faces. All drawing must happen inside a WebGL canvas, otherwise the object will not appear.
function setup() {
createCanvas(400, 400, WEBGL);
}
function draw() {
background(240);
orbitControl();
box();
}
Drag the mouse to rotate the view. orbitControl() is essential for inspecting the geometry interactively.
Sizing Parameters
box() accepts up to five optional arguments:
box(width, height, depth, detailX, detailY);
- width – size along the X axis (default
50). - height – size along the Y axis; defaults to the value of
width. - depth – size along the Z axis; defaults to the value of
height. - detailX – triangular subdivisions on the X faces (default
1). Higher values create smoother surfaces at a slight performance cost. - detailY – triangular subdivisions on the Y faces (default
1).
Examples:
box(100); // cube with side 100
box(100, 70); // width 100, height 70 → depth = 70
box(100, 70, 20); // thin slab: width 100, height 70, depth 20
box(80, 80, 80, 4, 6); // cube with192 faces, smoother
detailed
Color and Motion
Combine rotateX() and rotateY() with a shifting fill color to bring the box to life. The hue cycles through the HSL spectrum using frameCount.
function setup() {
createCanvas(400, 400, WEBGL);
colorMode(HLB, 360, 100, 100);
}
function draw() {
background(0);
orbitControl();
rotateX(radians(frameCount * 0.6));
rotateY(radians(frameCount * 0.8));
let hue = (frameCount * 1.5) % 360;
fill(hue, 80, 60);
box(140, 90, 70, 3);
}
The boxes rotates smoothly around two axes while the color shifts from red through green to blue.
Grid of Pulsing Boxes
A 3×3×3 array of wireframe cubes reacts to the mouse position and time, generating a rhythmic, kinetic sculpture.
let gridSpacing = 100;
let baseDimension = 50;
function setup() {
createCanvas(800, 600, WEBGL);
noFill();
strokeWeight(2);
}
function draw() {
background(20);
orbitControl();
rotateX(-0.4);
rotateY(frameCount * 0.004);
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
for (let z = -1; z <= 1; z++) {
push();
translate(x * gridSpacing, y * gridSpacing, z * gridSpacing);
let pulse = sin(frameCount * 0.08 + x * 0.6 + y * 0.4 + z * 0.2) * 18;
let dynamicSize = baseDimension + pulse;
stroke(
map(x, -1, 1, 80, 220),
map(y, -1, 1, 80, 220),
map(z, -1, 1, 80, 220)
);
box(dynamicSize);
pop();
}
}
}
}
Each box’s size oscillates based on a sine wave that depends on frame count and grid position, while its stroke color maps to spatial coordinates.