Create Complex 3D Shapes with Three.js ExtrudeGeometry

This article provides a step-by-step guide on how to create complex 3D shapes in Three.js using the ExtrudeGeometry class. You will learn how to define a detailed 2D path using THREE.Shape, configure extrusion options such as depth, bevels, and steps, and render the final 3D mesh in your scene.

Step 1: Define the 2D Shape

To create an extruded 3D object, you must first define its 2D profile using the THREE.Shape class. This class allows you to draw paths, lines, and curves. You can also create holes inside the shape to add complexity.

// Create a new 2D shape
const heartShape = new THREE.Shape();

// Draw a heart shape using bezier curves
heartShape.moveTo(25, 25);
heartShape.bezierCurveTo(25, 25, 20, 0, 0, 0);
heartShape.bezierCurveTo(-30, 0, -30, 35, -30, 35);
heartShape.bezierCurveTo(-30, 55, -10, 77, 25, 95);
heartShape.bezierCurveTo(60, 77, 80, 55, 80, 35);
heartShape.bezierCurveTo(80, 35, 80, 0, 50, 0);
heartShape.bezierCurveTo(35, 0, 25, 25, 25, 25);

// Optional: Add a hole in the middle of the shape
const holePath = new THREE.Path();
holePath.absarc(25, 45, 10, 0, Math.PI * 2, true);
heartShape.holes.push(holePath);

Step 2: Configure Extrusion Options

The ExtrudeGeometry class requires an options object to define how the 2D shape is projected into 3D space. Key properties include:

const extrudeSettings = {
    depth: 20,
    bevelEnabled: true,
    bevelThickness: 3,
    bevelSize: 2,
    bevelSegments: 5,
    steps: 1
};

Step 3: Generate the Geometry and Mesh

With the 2D shape and extrusion settings defined, instantiate the ExtrudeGeometry and apply a material. Using an array of two materials allows you to style the front/back faces differently from the extruded sides.

// Create the geometry
const geometry = new THREE.ExtrudeGeometry(heartShape, extrudeSettings);

// Create materials (Material index 0 is for the faces, index 1 is for the sides)
const frontMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const sideMaterial = new THREE.MeshStandardMaterial({ color: 0xaa0000 });

const materials = [frontMaterial, sideMaterial];

// Create the mesh and add it to the scene
const mesh = new THREE.Mesh(geometry, materials);
scene.add(mesh);

By adjusting the paths of your THREE.Shape and fine-tuning the extrudeSettings, you can create highly detailed, custom 3D models directly in your code without relying on external modeling software.