Dynamic Theming in Three.js: Implementing Dark and Light Mode Variants
Introduction
Modern web applications are expected to adapt to user preferences, particularly regarding dark and light color themes. While CSS handles this easily for DOM elements, bringing that same flexibility to 3D scenes in Three.js requires a more deliberate approach. We have recently introduced dark and light mode support to the EstreFlores/svgl project, ensuring our 3D visualizations remain visually consistent regardless of the system theme.
The Problem
Three.js scenes are often constructed with hardcoded color values for lights, materials, and background clears. When a user switches their operating system or browser theme, a static 3D scene can become jarring—potentially appearing too bright or too dim depending on the user's surrounding interface. Manually updating these values at runtime can be cumbersome if the scene state is fragmented.
The Solution: Reactive Theme Management
To manage these variants, we implemented a centralized configuration object that maps theme types to specific color properties. This allows us to toggle scene parameters instantly when the environment changes.
interface ThemeConfig {
background: string;
ambientIntensity: number;
materialColor: number;
}
const themes: Record<string, ThemeConfig> = {
light: { background: '#ffffff', ambientIntensity: 0.8, materialColor: 0x333333 },
dark: { background: '#1a1a1a', ambientIntensity: 0.2, materialColor: 0xffffff }
};
function applyTheme(scene: THREE.Scene, light: THREE.AmbientLight, theme: ThemeConfig) {
scene.background = new THREE.Color(theme.background);
light.intensity = theme.ambientIntensity;
// Update material properties accordingly
}
This approach encapsulates the visual state of the scene. By keeping these settings separated from the core rendering logic, we can easily extend support to additional themes or high-contrast modes without modifying our base geometry or animation code.
Practical Application
By leveraging this pattern in the EstreFlores/svgl project, we can listen for matchMedia events related to prefers-color-scheme. When a change is detected, we update the Three.js scene graph properties immediately. This makes the 3D elements feel like a native extension of the website's design system rather than an isolated canvas.
Key Takeaways
- Centralize your theme definitions to avoid scattered color hardcoding.
- Use a reactive approach to bridge system-level theme changes and your 3D canvas.
- Abstract material and light settings into a theme configuration object for cleaner updates.
Next time you build a 3D experience, treat your scene properties as state-driven rather than static configuration. Start by identifying the three most impactful elements in your scene—usually background, ambient lighting, and base material colors—and map those to your theme object first.
Generated with Gitvlg.com