Three.js LineSegments: Draw Disconnected Lines
In Three.js, drawing separate, disconnected lines requires using the
LineSegments class instead of the standard
Line or LineLoop classes. This article
explains how to define pairs of vertices within a
BufferGeometry and render them as individual,
non-continuous segments using LineSegments and
LineBasicMaterial.
Understanding LineSegments vs. Line
While the standard THREE.Line class connects vertices
sequentially in a continuous strip (Vertex A to B, B to C, C to D),
THREE.LineSegments treats every pair of vertices as an
independent segment.
In LineSegments, vertices are grouped in pairs of two: *
Vertices 0 and 1 form the first line segment. * Vertices 2 and 3 form
the second line segment. * Vertices 4 and 5 form the third line segment,
and so on.
If you have an odd number of vertices, the final vertex is ignored.
Step-by-Step Implementation
To create separate line segments, you must define your vertex
coordinates, bind them to a BufferGeometry, and instantiate
a LineSegments object.
1. Define the Vertices
Create a flat array of coordinates. In this example, we will define two separate, parallel line segments.
import * as THREE from 'three';
// Define vertices for two disconnected lines
// Line 1: from (-2, 0, 0) to (-2, 2, 0)
// Line 2: from (2, 0, 0) to (2, 2, 0)
const vertices = new Float32Array([
-2, 0, 0, // Segment 1: Start
-2, 2, 0, // Segment 1: End
2, 0, 0, // Segment 2: Start
2, 2, 0 // Segment 2: End
]);2. Create the Geometry
Instantiate a BufferGeometry and assign the vertices to
the position attribute.
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));3. Create the Material
Define a material to style the lines. LineBasicMaterial
is the standard choice for solid-colored lines.
const material = new THREE.LineBasicMaterial({
color: 0x00ff00,
linewidth: 1 // Note: linewidth > 1 is generally not supported by most WebGL platforms
});4. Instantiate and Add to Scene
Combine the geometry and material using the
THREE.LineSegments class and add the resulting object to
your Three.js scene.
const lineSegments = new THREE.LineSegments(geometry, material);
scene.add(lineSegments);By using THREE.LineSegments instead of
THREE.Line, the renderer will draw two distinct, parallel
vertical lines rather than a single continuous zig-zag path.