Render Mesh Outlines with Three.js EdgesGeometry
Rendering visual outlines of a 3D mesh is a common technique used to
highlight object boundaries, create wireframe overlays, or achieve a
stylized, blueprint-like aesthetic in web graphics. In Three.js, this is
most efficiently achieved using EdgesGeometry, which
identifies and extracts the sharp edges of a source geometry based on a
specified threshold angle. This article provides a direct, step-by-step
guide on how to configure and render these visual outlines alongside
your existing meshes.
To render outlines using EdgesGeometry, you need to pass
a source geometry to it, pair the resulting geometry with a line
material, and render it using LineSegments.
Here is the complete implementation code:
import * as THREE from 'three';
// 1. Create the main mesh
const geometry = new THREE.BoxGeometry(2, 2, 2);
const material = new THREE.MeshStandardMaterial({ color: 0x3498db });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// 2. Generate the edges geometry
// The second argument is the threshold angle in degrees.
const thresholdAngle = 15;
const edgesGeometry = new THREE.EdgesGeometry(geometry, thresholdAngle);
// 3. Create a line material and line segments
const lineMaterial = new THREE.LineBasicMaterial({
color: 0xffffff,
linewidth: 2 // Note: linewidth > 1 is not supported by most WebGL implementations
});
const outlines = new THREE.LineSegments(edgesGeometry, lineMaterial);
// 4. Add the outlines as a child of the mesh
mesh.add(outlines);Understanding the Key Components
EdgesGeometry(geometry, thresholdAngle): This helper class takes a standard geometry as its first argument. The second argument,thresholdAngle, is the minimum angle (in degrees) between the normals of two adjacent faces required to draw an edge. If the angle between adjacent faces is greater than this threshold, an outline is generated. Setting this value higher prevents internal edges on smoother surfaces from being rendered.LineSegments: UnlikeTHREE.Line, which connects all vertices sequentially in a continuous strip,LineSegmentsrenders independent line segments. This is required becauseEdgesGeometrygenerates disjointed line segments that should not be connected by diagonal lines.- Parent-Child Relationship: By adding the
outlinesobject directly to themesh(mesh.add(outlines)), the outline will automatically inherit the position, rotation, and scale transforms of the parent mesh, keeping the outline perfectly aligned during animations.