Create a Grid Floor in Three.js with GridHelper

This article provides a straightforward, step-by-step guide on how to construct a grid reference floor in a Three.js 3D scene using the built-in GridHelper class. You will learn how to initialize the helper, customize its size and colors, and position it correctly within your virtual environment to serve as a visual ground reference.

Understanding the GridHelper Class

The GridHelper is a convenient, pre-built object in Three.js that creates a two-dimensional grid of lines. It is highly optimized and prevents you from having to manually draw individual line geometries for a ground guide.

The constructor for GridHelper accepts four optional parameters:

const gridHelper = new THREE.GridHelper(size, divisions, colorCenterLine, colorGrid);

Step-by-Step Implementation

To add a grid floor to your Three.js project, follow these steps:

1. Initialize the GridHelper

Define the size, resolution, and colors of your grid, then instantiate the GridHelper class.

import * as THREE from 'three';

// Define grid parameters
const gridWidth = 50;         // Total width and depth of the grid floor
const gridDivisions = 50;     // Number of grid squares along each axis
const centerLineColor = 0xff0000; // Red color for the main axes lines
const gridLineColor = 0x444444;   // Dark gray color for the rest of the grid

// Create the GridHelper instance
const gridHelper = new THREE.GridHelper(gridWidth, gridDivisions, centerLineColor, gridLineColor);

2. Add the Grid to the Scene

Once created, add the helper object directly to your Three.js scene graph.

// Assuming 'scene' is your pre-existing THREE.Scene instance
scene.add(gridHelper);

By default, the GridHelper is drawn on the XZ plane, which represents a flat, horizontal floor in Three.js’s coordinate system.


Customizing the Grid Position and Orientation

Adjusting the Height (Y-Axis)

If your 3D models sit exactly on the origin (y = 0), you might experience visual glitching (z-fighting) between the grid lines and your objects’ bottom faces. You can offset the grid slightly downward to prevent this:

gridHelper.position.y = -0.01; // Lowers the grid slightly below the origin

Rotating the Grid (Vertical Walls)

To use the GridHelper as a vertical wall guide (e.g., on the XY or YZ plane) instead of a floor, rotate the helper on the appropriate axis:

// Rotate 90 degrees to align with the XY plane (vertical wall)
gridHelper.rotation.x = Math.PI / 2;