Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Rendering and Animating 3D Cubes with p5.js

Tech 2

To work with 3D geometries in p5.js, enable WebGL rendering by passing WEBGL to createCanvas(). The box() function generates cube geometries with configurable dimensions and subdivision levels.

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

function draw() {
  background(240);
  rotateX(PI / 6);
  rotateY(PI / 4);
  box(120);
}

Dimensional Parameters

The box() signature accepts up to five arguments: box(w, h, d, detailX, detailY).

  • w: Width in pixels (default 50)
  • h: Height in pixels (defaults to width if omitted)
  • d: Depth in pixels (defaults too height if omitted)
  • detailX/Y: Tessellation level for surface smoothing

When supplying a single argument, all dimensions equal that value. With two arguments, depth inherits the height value. Three explicit arguments define distinct width, height, and depth.

// Perfect cube
box(100);

// Rectangular prism
box(100, 60, 40);

Surface Appearance

Visual properties must be defined before calling box().

Solid fills use fill():

fill(100, 150, 255);
box(80);

Wireframe rendering disables filling and sets stroke properties:

noFill();
stroke(40);
strokeWeight(2);
box(80);

Texture Mapping

Apply images or video streams as surface materials using texture(). Load media within preload() to ensure availability before rendering.

let img;

function preload() {
  img = loadImage('assets/brick.jpg');
}

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

function draw() {
  background(220);
  rotateZ(frameCount * 0.01);
  texture(img);
  box(150);
}

For animated textures, reference the media object inside draw() to update frames continuously.

Video textures require hiding the DOM element to prevent overlay:

let vid;

function preload() {
  vid = createVideo('assets/clip.mp4');
  vid.hide();
}

function setup() {
  createCanvas(640, 480, WEBGL);
  vid.loop();
  vid.volume(0);
}

function draw() {
  background(20);
  rotateY(frameCount * 0.02);
  texture(vid);
  box(200);
}

Lighting

Basic ilumination enhances depth perception. Combine ambient and directional lights before drawing:

ambientLight(120);
directionalLight(255, 255, 255, 1, 1, -1);
box(100);

Continuous Animation

Moving geometries require the draw() loop. Use frameCount or millis() for time-based transformations.

function draw() {
  background(200);
  
  // Orbital rotation
  rotateX(frameCount * 0.03);
  rotateY(frameCount * 0.02);
  
  box(100);
}

Implementation Patterns

Cascading Rotations

Isolate transformations using push() and pop() to create layered effects without cumulative coordinate changes:

let angle = 0;
const count = 10;
const offset = PI / 12;

function setup() {
  createCanvas(500, 500, WEBGL);
  noStroke();
}

function draw() {
  background(230);
  lights();
  
  for (let i = 0; i < count; i++) {
    let shade = map(i, 0, count - 1, 50, 255);
    push();
    fill(shade);
    rotateY(angle + offset * i);
    rotateX(angle / 2 + offset * i);
    box(180);
    pop();
  }
  
  angle += 0.015;
}

Distributed Voxel Clouds

Position multiple cubes using coordinate arrays:

let nodes = [];

function setup() {
  createCanvas(400, 400, WEBGL);
  
  // Generate positions
  for (let i = 0; i < 12; i++) {
    nodes.push([
      random(-100, 100),
      random(-100, 100),
      random(-100, 100)
    ]);
  }
}

function draw() {
  background(240);
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  
  for (let pos of nodes) {
    push();
    translate(pos[0], pos[1], pos[2]);
    box(25);
    pop();
  }
}

Volumetric Grids

Nested loops create three-dimensional matrices:

function draw() {
  background(220);
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  
  const gap = 40;
  const size = 15;
  
  for (let x = -2; x <= 2; x++) {
    for (let y = -2; y <= 2; y++) {
      for (let z = -2; z <= 2; z++) {
        push();
        translate(x * gap, y * gap, z * gap);
        box(size);
        pop();
      }
    }
  }
}

Recursive Subdivision

Generate fractal-like structures through self-referential rendering:

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

function draw() {
  background(240);
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  subdivideBox(160, 3);
}

function subdivideBox(dim, depth) {
  box(dim);
  
  if (depth > 1) {
    let newDim = dim / 2;
    let offset = dim / 2;
    
    const positions = [
      [-offset, -offset, -offset],
      [-offset, -offset, offset],
      [-offset, offset, -offset],
      [-offset, offset, offset],
      [offset, -offset, -offset],
      [offset, -offset, offset],
      [offset, offset, -offset],
      [offset, offset, offset]
    ];
    
    for (let pos of positions) {
      push();
      translate(pos[0], pos[1], pos[2]);
      subdivideBox(newDim, depth - 1);
      pop();
    }
  }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.