How to Draw a Line Strip in Three.js
In Three.js, drawing a continuous line strip across multiple
coordinates is a fundamental task for visualizing paths, trajectories,
or wireframe outlines. This guide provides a straightforward,
step-by-step tutorial on how to define points using 3D vectors,
configure a line material, and use the THREE.Line class to
render a seamless, connected path in your WebGL scene.
Step 1: Define the Points
To draw a line, you first need to define the vertices (points) that
the line will connect. Create an array containing
THREE.Vector3 objects representing the coordinates of each
point in 3D space.
const points = [];
points.push(new THREE.Vector3(-10, 0, 0));
points.push(new THREE.Vector3(0, 10, 0));
points.push(new THREE.Vector3(10, 0, 0));
points.push(new THREE.Vector3(0, -10, 0));
points.push(new THREE.Vector3(-10, 0, 0)); // Connects back to the startStep 2: Create the Geometry
Three.js uses THREE.BufferGeometry to store vertex data.
You can easily feed your array of points into the geometry using the
.setFromPoints() method.
const geometry = new THREE.BufferGeometry().setFromPoints(points);Step 3: Define the Line Material
To make the line visible, you must define a material.
THREE.LineBasicMaterial is the standard choice for solid
lines. You can customize properties such as color.
const material = new THREE.LineBasicMaterial({
color: 0x00ff00, // Green
linewidth: 1 // Note: Most WebGL platforms only support a width of 1
});Step 4: Instantiate the THREE.Line Class
Pass the geometry and the material into the THREE.Line
constructor. The THREE.Line class automatically connects
the points in the sequence they were added to the array, creating a
continuous line strip.
const line = new THREE.Line(geometry, material);Step 5: Add the Line to Your Scene
Finally, add the created line object to your Three.js scene so that it is included in the render loop.
scene.add(line);Complete Code Example
Here is how the complete implementation looks when combined:
import * as THREE from 'three';
// Scene setup
const scene = new THREE.Scene();
// 1. Define points
const points = [
new THREE.Vector3(-5, 0, 0),
new THREE.Vector3(0, 5, 0),
new THREE.Vector3(5, 0, 0),
new THREE.Vector3(0, -5, 0)
];
// 2. Create geometry
const geometry = new THREE.BufferGeometry().setFromPoints(points);
// 3. Create material
const material = new THREE.LineBasicMaterial({ color: 0xff0000 });
// 4. Create the continuous line
const line = new THREE.Line(geometry, material);
// 5. Add to scene
scene.add(line);