Overview
TheLabelRenderer class manages 2D HTML labels that are rendered on top of the 3D scene using CSS2D rendering. Labels automatically position themselves relative to their parent 3D objects and can be toggled with layer visibility.
Internally uses THREE.CSS2DRenderer to overlay HTML elements onto the map canvas.
Constructor
Mapbox GL JS map instance
- Creates a CSS2D renderer
- Sets up a canvas overlay positioned absolutely over the map
- Attaches resize handlers to maintain proper dimensions
- Appends the label canvas to the map container
Properties
renderer
The THREE.CSS2DRenderer instance used for rendering labels.scene
The Three.js scene containing labeled objects.camera
The Three.js camera used for label positioning.Methods
render
Renders labels for the current scene and camera.Three.js scene containing objects with labels
Three.js camera for determining label positions
Promise<void>
Example:
setSize
Updates the renderer dimensions.Width in pixels
Height in pixels
toggleLabels
Toggles visibility of labels for a specific layer.The Mapbox layer ID
Whether labels should be visible
Promise<void>
Example:
setVisibility
Internal method to set visibility of labels matching specific criteria.Layer ID to filter labels
Target visibility state
The scene containing labels
The camera for rendering
The renderer instance
- Iterates through the renderer’s cache list
- Filters labels by layer ID
- Respects
alwaysVisibleproperty on labels - Re-renders affected labels
dispose
Cleans up and removes the label renderer.- Removes the DOM element from the map container
- Clears the renderer object
- Should be called before removing the map or changing styles
Label Canvas Properties
The label canvas overlay has the following default properties:Usage Example
Integration with Threebox
The LabelRenderer is automatically integrated with Threebox when labels are used:Creating Labels on Objects
Objects can have labels added using theaddLabel method:
The label text content
If true, label shows even when layer is hidden (unless explicitly toggled)
Automatic Resize Handling
The LabelRenderer automatically handles map resize events:Performance Considerations
- Labels are rendered using CSS transforms for optimal performance
- The renderer maintains a cache list to avoid redundant renders
- Label visibility toggling uses the cache for efficient filtering
- Large numbers of labels (>1000) may impact performance
Notes
- Labels use CSS2D rendering, so they’re always rendered on top of the 3D scene
- Label positions update automatically as objects move or camera changes
- The label canvas has
z-index: 0by default (below Mapbox controls) - Labels are automatically disposed when their parent objects are removed
- The
alwaysVisibleproperty on labels is respected during visibility toggling