Extract Evenly Spaced Points from Three.js Curves
This article explains how to use the getSpacedPoints
method in Three.js to extract a set of equidistant points along a 3D
curve. You will learn the difference between standard curve sampling and
arc-length sampling, see a practical code implementation, and understand
how to use these points to create smooth paths or animate objects at a
constant speed.
Understanding getSpacedPoints vs getPoints
When working with curves in Three.js (such as
CatmullRomCurve3 or CubicBezierCurve), you
often need to retrieve coordinate points along the path. Three.js
provides two main methods for this:
getPoints(divisions): Samples the curve at equal intervals of the curve’s parametric \(t\) value (from 0 to 1). This often causes points to cluster together in tight bends and spread out on straight sections.getSpacedPoints(divisions): Samples the curve using cumulative segment lengths (arc length). This ensures that the distance along the curve between any two consecutive points is identical, regardless of the curve’s geometry.
How to Use getSpacedPoints
To extract evenly spaced points, define your curve, call
getSpacedPoints with the desired number of divisions, and
use the returned array of vector objects.
Here is a practical JavaScript example:
import * as THREE from 'three';
// 1. Define the control points for the curve
const controlPoints = [
new THREE.Vector3(-10, 0, 0),
new THREE.Vector3(-5, 5, 5),
new THREE.Vector3(0, 0, 10),
new THREE.Vector3(5, -5, 5),
new THREE.Vector3(10, 0, 0)
];
// 2. Create the curve
const curve = new THREE.CatmullRomCurve3(controlPoints);
// 3. Extract evenly spaced points
// Passing 50 divisions returns an array of 51 equidistant Vector3 points
const divisions = 50;
const spacedPoints = curve.getSpacedPoints(divisions);
// 4. Use the points to create a visual line representation
const geometry = new THREE.BufferGeometry().setFromPoints(spacedPoints);
const material = new THREE.LineBasicMaterial({ color: 0xff0000 });
const line = new THREE.Line(geometry, material);
// Add the line to your Three.js scene
scene.add(line);Key Considerations
- Point Count: The
getSpacedPoints(divisions)method takes the number of subdivisions as an argument. The returned array will containdivisions + 1points, which includes both the start and end points of the curve. - Performance: Calculating equidistant points requires Three.js to calculate the arc length of the curve by caching segment lengths. For highly dynamic curves that change shape every frame, calling this method repeatedly can impact rendering performance.
- Constant Speed Animation: If you need to animate an
object along a path at a constant velocity, use
getSpacedPointsto generate the path coordinates. Stepping through this array linearly will prevent the object from accelerating or decelerating unnaturally.