How to Change Mesh Render Order in Three.js
In Three.js, controlling the sequence in which 3D objects are drawn
to the screen is crucial for resolving depth conflicts, managing
transparency, and creating custom visual overlays. This article explains
how to use the renderOrder property, manipulate material
depth settings, and configure the WebGL renderer to precisely control
the rendering order of specific meshes within your scene graph.
Understanding the
renderOrder Property
Every object inheriting from THREE.Object3D (including
meshes, groups, and lines) possesses a renderOrder
property. By default, this value is set to 0.
When the WebGL renderer draws your scene, it sorts objects based on
their renderOrder in ascending order. Objects with lower
renderOrder values are rendered first, while objects with
higher values are rendered later.
To change the render order of a specific mesh, assign a positive or
negative integer to its renderOrder property:
// This mesh will be rendered first
backgroundMesh.renderOrder = -1;
// This mesh uses the default render order
standardMesh.renderOrder = 0;
// This mesh will be rendered last (on top of others, depending on depth settings)
overlayMesh.renderOrder = 1;Configuring Depth Testing for Overlays
Simply changing the renderOrder may not achieve the
desired visual result if depth testing is enabled. By default, the WebGL
renderer checks the depth buffer to ensure that objects physically
behind other objects are obscured, regardless of their rendering
order.
If you want a mesh with a higher renderOrder to always
appear on top of other meshes (like a user interface element or a 3D
gizmo), you must disable its material’s depth testing:
const overlayMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000,
depthTest: false,
depthWrite: false
});
const overlayMesh = new THREE.Mesh(geometry, overlayMaterial);
overlayMesh.renderOrder = 999; // Render last
scene.add(overlayMesh);depthTest: false: Prevents the mesh from being hidden by objects that are closer to the camera.depthWrite: false: Prevents the mesh from writing to the depth buffer, ensuring it does not block subsequently rendered objects.
Disabling Renderer Auto-Sorting
Three.js automatically sorts objects before rendering to optimize performance and handle transparent objects correctly. Transparent objects are sorted from back-to-front, while opaque objects are sorted from front-to-back.
If you want absolute control over the rendering order purely based on
your scene graph insertion order or manual renderOrder
assignments, you can disable the renderer’s automatic sorting:
renderer.sortObjects = false;Note: Disabling sortObjects is rarely recommended as
it can cause rendering artifacts with transparent materials, but it can
be useful for highly specialized 2D or isometric rendering
pipelines.