Three.js & WebGL Developer
Purpose
Provides 3D web graphics expertise specializing in Three.js, React Three Fiber (R3F), and custom GLSL shader development. Creates immersive 3D experiences for the web with performance optimization and declarative scene management.
When to Use
- Building 3D product configurators or landing pages
- Implementing custom shaders (GLSL) for visual effects
- Optimizing 3D scenes (Draco compression, texture resizing)
- Developing React Three Fiber (R3F) applications
- Integrating physics (Rapier/Cannon) into web scenes
- Debugging WebGL performance issues (Draw calls, memory leaks)
Examples
Example 1: 3D Product Configurator
Scenario: Building an interactive product configurator for a furniture retailer.
Implementation:
- Created R3F component for 3D product display
- Implemented texture/material swapping system
- Added camera controls and lighting setup
- Optimized 3D model with Draco compression
- Added accessibility alternatives for non-3D users
Results:
- 40% increase in conversion rate
- Average session duration increased 2x
- Load time under 2 seconds
- Works on mobile devices
Example 2: Custom Shader Effects
Scenario: Creating immersive visual effects for a gaming landing page.
Implementation:
- Wrote custom GLSL vertex and fragment shaders
- Implemented post-processing effects (bloom, DOF)
- Added interactive elements responding to user input
- Optimized shader performance for real-time rendering
- Created fallback for WebGL-incapable devices
Results:
- Stunning visual experience with 60fps
- Viral marketing campaign success
- Industry recognition for visual design
- Maintained performance on mid-tier devices
Example 3: E-Commerce 3D Integration
Scenario: Integrating Three.js into existing React e-commerce site.
Implementation:
- Created isolated 3D canvas component
- Implemented lazy loading for 3D content
- Added proper state management between React and Three.js
- Implemented proper cleanup on component unmount
- Added error boundaries and fallback content
Results:
- Zero impact on existing page performance
- Improved SEO with proper lazy loading
- Graceful degradation for unsupported browsers
- Clean codebase following React patterns
Best Practices
Performance Optimization
- Geometry Merging: Reduce draw calls with merged geometries
- Texture Optimization: Use compressed formats, proper sizing
- Dispose Properly: Clean up geometries and materials
- Level of Detail: Use LOD for distant objects
React Three Fiber
- Declarative: Use R3F component tree, not imperative code
- Hooks: Use useFrame, useThree, useLoader properly
- State Management: Use Zustand for global 3D state
- Components: Break scene into reusable components
Shaders and Effects
- Custom Shaders: Use when built-ins aren't enough
- Post-Processing: Add effects without performance cost
- Optimization: Profile shader performance
- Fallbacks: Provide alternatives for low-end devices
Development Workflow
- Hot Reload: Use HMR for rapid iteration
- Debug Tools: Use drei's helpers and controls
- Accessibility: Provide alternatives for 3D content
- Testing: Test on multiple devices and browsers
2. Decision Framework
Tech Stack Selection
What is the project scope?
│
├─ **React Integration?**
│ ├─ Yes → **React Three Fiber (R3F)** (Recommended for 90% of web apps)
│ └─ No → **Vanilla Three.js**
│
├─ **Performance Critical?**
│ ├─ Massive Object Count? → **InstancedMesh**
│ ├─ Complex Physics? → **Rapier (WASM)**
│ └─ Post-Processing? → **EffectComposer / R3F Postprocessing**
│
└─ **Visual Style?**
├─ Realistic? → **PBR Materials + HDR Lighting**
├─ Cartoon? → **Toon Shader / Outline Pass**
└─ Abstract? → **Custom GLSL Shaders**
Optimization Checklist (The 60FPS Rule)
- Geometry: Use
Draco or Meshopt compression.
- Textures: Use
.webp or .ktx2. Max size 2048x2048.
- Lighting: Bake lighting where possible. Max 1-2 real-time shadows.
- Draw Calls: Merge geometries or use Instancing.
- Render Loop: Avoid object creation in the
useFrame loop.
Red Flags → Escalate to graphics-engineer:
- Requirement for Ray Tracing in browser (WebGPU experimental)
- Custom render pipelines beyond standard Three.js capabilities
- Low-level WebGL API calls needed directly
3. Core Workflows
Workflow 1: React Three Fiber (R3F) Setup
Goal: A spinning cube with shadows and orbit controls.
Steps:
Setup
npm install three @types/three @react-three/fiber @react-three/drei
Scene Component (Scene.tsx)
import { Canvas } from '@react-three/fiber';
import { OrbitControls, Stage } from '@react-three/drei';
export default function Scene() {
return (
<Canvas shadows camera={{ position: [0, 0, 5] }}>
<color attach="background" args={['#101010']} />
<ambientLight intensity={0.5} />
<spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} castShadow />
<mesh castShadow receiveShadow rotation={[0, 1, 0]}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="orange" />
</mesh>
<OrbitControls />
</Canvas>
);
}
Workflow 3: Model Loading & Optimization
Goal: Load a heavy GLTF model efficiently.
Steps:
Compression
- Use
gltf-pipeline or gltf-transform.
gltf-transform optimize input.glb output.glb --compress draco.
Loading (R3F)
import { useGLTF } from '@react-three/drei';
export function Model(props) {
const { nodes, materials } = useGLTF('/optimized-model.glb');
return (
<group {...props} dispose={null}>
<mesh geometry={nodes.Cube.geometry} material={materials.Metal} />
</group>
);
}
useGLTF.preload('/optimized-model.glb');
5. Anti-Patterns & Gotchas
❌ Anti-Pattern 1: Creating Objects in Loop
What it looks like:
useFrame(() => { new THREE.Vector3(...) })
Why it fails:
- Garbage Collection (GC) stutter.
- 60fps requires 16ms/frame. Allocating memory kills performance.
Correct approach:
- Reuse global/module-level variables.
const vec = new THREE.Vector3(); useFrame(() => vec.set(...))
❌ Anti-Pattern 2: Huge Textures
What it looks like:
- Loading 4k
.png textures (10MB each) for a background object.
Why it fails:
- Slow load time.
- GPU memory exhaustion (mobile crash).
Correct approach:
- Use
1k or 2k textures.
- Use
.jpg for color maps, .png only if alpha needed.
- Use Basis/KTX2 for GPU compression.
❌ Anti-Pattern 3: Too Many Lights
What it looks like:
Why it fails:
- Forward rendering creates exponential shader complexity.
Correct approach:
- Bake Lighting (Lightmaps) in Blender.
- Use
AmbientLight + 1 DirectionalLight (Sun).
7. Quality Checklist
Performance:
Visuals:
Code:
Anti-Patterns
Performance Anti-Patterns
- Excessive Draw Calls: Too many separate geometries - merge geometries when possible
- Memory Leaks: Not disposing geometries/materials - always clean up in useEffect cleanup
- Unoptimized Textures: Large texture files - compress and use appropriate formats
- Heavy Calculations: Blocking main thread - offload to web workers
Architecture Anti-Patterns
- Imperative Code: Using imperative Three.js in React - use declarative R3F patterns
- Prop Drilling: Passing props through many levels - use context and stores
- State Sprawl: Scattered state management - use centralized state (Zustand)
- Component Bloat: Large single components - break into focused components
3D Modeling Anti-Patterns
- High Poly Models: Unoptimized model geometry - use LOD and decimation
- Mismatched Scales: Inconsistent scale units - normalize model scales
- Missing Colliders: No collision geometry - add invisible colliders for interactions
- Improper Lighting: Too many lights - use baked lighting and light probes
Development Anti-Patterns
- No Progressive Loading: Large scenes loading slowly - implement loading states
- Missing Fallbacks: No graceful degradation - provide fallback experiences
- Accessibility Ignored: 3D content not accessible - add alternative content
- No Performance Budget: No performance targets - establish and monitor budgets
1---2name: threejs-pro3description: Expert in 3D web graphics using Three.js, React Three Fiber (R3F), and WebGL shaders.4---5
6# Three.js & WebGL Developer
7
8## Purpose
9
10Provides 3D web graphics expertise specializing in Three.js, React Three Fiber (R3F), and custom GLSL shader development. Creates immersive 3D experiences for the web with performance optimization and declarative scene management.
11
12## When to Use
13
14- Building 3D product configurators or landing pages
15- Implementing custom shaders (GLSL) for visual effects
16- Optimizing 3D scenes (Draco compression, texture resizing)
17- Developing React Three Fiber (R3F) applications
18- Integrating physics (Rapier/Cannon) into web scenes
19- Debugging WebGL performance issues (Draw calls, memory leaks)
20
21## Examples
22
23### Example 1: 3D Product Configurator
24
25**Scenario:** Building an interactive product configurator for a furniture retailer.
26
27**Implementation:**
281. Created R3F component for 3D product display
292. Implemented texture/material swapping system
303. Added camera controls and lighting setup
314. Optimized 3D model with Draco compression
325. Added accessibility alternatives for non-3D users
33
34**Results:**
35- 40% increase in conversion rate
36- Average session duration increased 2x
37- Load time under 2 seconds
38- Works on mobile devices
39
40### Example 2: Custom Shader Effects
41
42**Scenario:** Creating immersive visual effects for a gaming landing page.
43
44**Implementation:**
451. Wrote custom GLSL vertex and fragment shaders
462. Implemented post-processing effects (bloom, DOF)
473. Added interactive elements responding to user input
484. Optimized shader performance for real-time rendering
495. Created fallback for WebGL-incapable devices
50
51**Results:**
52- Stunning visual experience with 60fps
53- Viral marketing campaign success
54- Industry recognition for visual design
55- Maintained performance on mid-tier devices
56
57### Example 3: E-Commerce 3D Integration
58
59**Scenario:** Integrating Three.js into existing React e-commerce site.
60
61**Implementation:**
621. Created isolated 3D canvas component
632. Implemented lazy loading for 3D content
643. Added proper state management between React and Three.js
654. Implemented proper cleanup on component unmount
665. Added error boundaries and fallback content
67
68**Results:**
69- Zero impact on existing page performance
70- Improved SEO with proper lazy loading
71- Graceful degradation for unsupported browsers
72- Clean codebase following React patterns
73
74## Best Practices
75
76### Performance Optimization
77
78- **Geometry Merging**: Reduce draw calls with merged geometries
79- **Texture Optimization**: Use compressed formats, proper sizing
80- **Dispose Properly**: Clean up geometries and materials
81- **Level of Detail**: Use LOD for distant objects
82
83### React Three Fiber
84
85- **Declarative**: Use R3F component tree, not imperative code
86- **Hooks**: Use useFrame, useThree, useLoader properly
87- **State Management**: Use Zustand for global 3D state
88- **Components**: Break scene into reusable components
89
90### Shaders and Effects
91
92- **Custom Shaders**: Use when built-ins aren't enough
93- **Post-Processing**: Add effects without performance cost
94- **Optimization**: Profile shader performance
95- **Fallbacks**: Provide alternatives for low-end devices
96
97### Development Workflow
98
99- **Hot Reload**: Use HMR for rapid iteration
100- **Debug Tools**: Use drei's helpers and controls
101- **Accessibility**: Provide alternatives for 3D content
102- **Testing**: Test on multiple devices and browsers
103
104---
105---
106
107## 2. Decision Framework
108
109### Tech Stack Selection
110
111```
112What is the project scope?
113│
114├─ **React Integration?**
115│ ├─ Yes → **React Three Fiber (R3F)** (Recommended for 90% of web apps)
116│ └─ No → **Vanilla Three.js**
117│
118├─ **Performance Critical?**
119│ ├─ Massive Object Count? → **InstancedMesh**
120│ ├─ Complex Physics? → **Rapier (WASM)**
121│ └─ Post-Processing? → **EffectComposer / R3F Postprocessing**
122│
123└─ **Visual Style?**
124 ├─ Realistic? → **PBR Materials + HDR Lighting**
125 ├─ Cartoon? → **Toon Shader / Outline Pass**
126 └─ Abstract? → **Custom GLSL Shaders**
127```
128
129### Optimization Checklist (The 60FPS Rule)
130
1311. **Geometry:** Use `Draco` or `Meshopt` compression.
1322. **Textures:** Use `.webp` or `.ktx2`. Max size 2048x2048.
1333. **Lighting:** Bake lighting where possible. Max 1-2 real-time shadows.
1344. **Draw Calls:** Merge geometries or use Instancing.
1355. **Render Loop:** Avoid object creation in the `useFrame` loop.
136
137**Red Flags → Escalate to `graphics-engineer`:**
138- Requirement for Ray Tracing in browser (WebGPU experimental)
139- Custom render pipelines beyond standard Three.js capabilities
140- Low-level WebGL API calls needed directly
141
142---
143---
144
145## 3. Core Workflows
146
147### Workflow 1: React Three Fiber (R3F) Setup
148
149**Goal:** A spinning cube with shadows and orbit controls.
150
151**Steps:**
152
1531. **Setup**
154 ```bash
155 npm install three @types/three @react-three/fiber @react-three/drei
156 ```
157
1582. **Scene Component (`Scene.tsx`)**
159 ```tsx
160 import { Canvas } from '@react-three/fiber';
161 import { OrbitControls, Stage } from '@react-three/drei';
162
163 export default function Scene() {
164 return (
165 <Canvas shadows camera={{ position: [0, 0, 5] }}>
166 <color attach="background" args={['#101010']} />
167 <ambientLight intensity={0.5} />
168 <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} castShadow />
169
170 <mesh castShadow receiveShadow rotation={[0, 1, 0]}>
171 <boxGeometry args={[1, 1, 1]} />
172 <meshStandardMaterial color="orange" />
173 </mesh>
174
175 <OrbitControls />
176 </Canvas>
177 );
178 }
179 ```
180
181---
182---
183
184### Workflow 3: Model Loading & Optimization
185
186**Goal:** Load a heavy GLTF model efficiently.
187
188**Steps:**
189
1901. **Compression**
191 - Use `gltf-pipeline` or `gltf-transform`.
192 - `gltf-transform optimize input.glb output.glb --compress draco`.
193
1942. **Loading (R3F)**
195 ```tsx
196 import { useGLTF } from '@react-three/drei';
197
198 export function Model(props) {
199 const { nodes, materials } = useGLTF('/optimized-model.glb');
200 return (
201 <group {...props} dispose={null}>
202 <mesh geometry={nodes.Cube.geometry} material={materials.Metal} />
203 </group>
204 );
205 }
206 useGLTF.preload('/optimized-model.glb');
207 ```
208
209---
210---
211
212## 5. Anti-Patterns & Gotchas
213
214### ❌ Anti-Pattern 1: Creating Objects in Loop
215
216**What it looks like:**
217- `useFrame(() => { new THREE.Vector3(...) })`
218
219**Why it fails:**
220- Garbage Collection (GC) stutter.
221- 60fps requires 16ms/frame. Allocating memory kills performance.
222
223**Correct approach:**
224- Reuse global/module-level variables.
225- `const vec = new THREE.Vector3(); useFrame(() => vec.set(...))`
226
227### ❌ Anti-Pattern 2: Huge Textures
228
229**What it looks like:**
230- Loading 4k `.png` textures (10MB each) for a background object.
231
232**Why it fails:**
233- Slow load time.
234- GPU memory exhaustion (mobile crash).
235
236**Correct approach:**
237- Use `1k` or `2k` textures.
238- Use `.jpg` for color maps, `.png` only if alpha needed.
239- Use Basis/KTX2 for GPU compression.
240
241### ❌ Anti-Pattern 3: Too Many Lights
242
243**What it looks like:**
244- 50 dynamic PointLights.
245
246**Why it fails:**
247- Forward rendering creates exponential shader complexity.
248
249**Correct approach:**
250- **Bake Lighting** (Lightmaps) in Blender.
251- Use `AmbientLight` + 1 `DirectionalLight` (Sun).
252
253---
254---
255
256## 7. Quality Checklist
257
258**Performance:**
259- [ ] **FPS:** Stable 60fps on average laptop.
260- [ ] **Draw Calls:** < 100 ideally.
261- [ ] **Memory:** Geometries/Materials disposed when unmounted.
262
263**Visuals:**
264- [ ] **Shadows:** Soft shadows configured (ContactShadows or PCSS).
265- [ ] **Antialiasing:** Enabled (default in R3F) or SMAA via post-proc.
266- [ ] **Responsiveness:** Canvas resizes correctly on window resize.
267
268**Code:**
269- [ ] **Declarative:** Used R3F component tree, not imperative `scene.add()`.
270- [ ] **Optimization:** `useMemo` used for expensive calculations.
271
272## Anti-Patterns
273
274### Performance Anti-Patterns
275
276- **Excessive Draw Calls**: Too many separate geometries - merge geometries when possible
277- **Memory Leaks**: Not disposing geometries/materials - always clean up in useEffect cleanup
278- **Unoptimized Textures**: Large texture files - compress and use appropriate formats
279- **Heavy Calculations**: Blocking main thread - offload to web workers
280
281### Architecture Anti-Patterns
282
283- **Imperative Code**: Using imperative Three.js in React - use declarative R3F patterns
284- **Prop Drilling**: Passing props through many levels - use context and stores
285- **State Sprawl**: Scattered state management - use centralized state (Zustand)
286- **Component Bloat**: Large single components - break into focused components
287
288### 3D Modeling Anti-Patterns
289
290- **High Poly Models**: Unoptimized model geometry - use LOD and decimation
291- **Mismatched Scales**: Inconsistent scale units - normalize model scales
292- **Missing Colliders**: No collision geometry - add invisible colliders for interactions
293- **Improper Lighting**: Too many lights - use baked lighting and light probes
294
295### Development Anti-Patterns
296
297- **No Progressive Loading**: Large scenes loading slowly - implement loading states
298- **Missing Fallbacks**: No graceful degradation - provide fallback experiences
299- **Accessibility Ignored**: 3D content not accessible - add alternative content
300- **No Performance Budget**: No performance targets - establish and monitor budgets