threejs-pro
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseThree.js & WebGL Developer
Three.js & WebGL 开发者
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.
提供专注于Three.js、React Three Fiber (R3F)和自定义GLSL着色器开发的3D网页图形技术支持。通过性能优化和声明式场景管理,为网页打造沉浸式3D体验。
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)
- 构建3D产品配置器或落地页
- 实现自定义着色器(GLSL)以添加视觉效果
- 优化3D场景(Draco压缩、纹理调整大小)
- 开发React Three Fiber (R3F)应用
- 在网页场景中集成物理引擎(Rapier/Cannon)
- 调试WebGL性能问题(绘制调用、内存泄漏)
Examples
案例
Example 1: 3D Product Configurator
案例1:3D产品配置器
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
场景: 为家具零售商构建交互式产品配置器。
实现方案:
- 创建用于3D产品展示的R3F组件
- 实现纹理/材质切换系统
- 添加相机控制和灯光设置
- 使用Draco压缩优化3D模型
- 为非3D用户添加无障碍替代方案
成果:
- 转化率提升40%
- 平均会话时长增加2倍
- 加载时间控制在2秒以内
- 支持移动设备访问
Example 2: Custom Shader Effects
案例2:自定义着色器效果
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
场景: 为游戏落地页打造沉浸式视觉效果。
实现方案:
- 编写自定义GLSL顶点和片段着色器
- 实现后期处理效果( bloom、景深DOF)
- 添加响应用户输入的交互元素
- 优化着色器性能以实现实时渲染
- 为不支持WebGL的设备提供降级方案
成果:
- 实现60fps的惊艳视觉体验
- 病毒式营销活动取得成功
- 视觉设计获得行业认可
- 在中端设备上仍能保持良好性能
Example 3: E-Commerce 3D Integration
案例3:电商3D集成
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
场景: 将Three.js集成到现有React电商网站中。
实现方案:
- 创建独立的3D画布组件
- 为3D内容实现懒加载
- 实现React与Three.js之间的状态管理
- 在组件卸载时执行正确的清理操作
- 添加错误边界和降级内容
成果:
- 对现有页面性能无任何影响
- 通过合理的懒加载提升SEO表现
- 对不支持的浏览器实现优雅降级
- 遵循React模式的整洁代码库
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
- 几何体合并:通过合并几何体减少绘制调用
- 纹理优化:使用压缩格式、合理调整尺寸
- 正确释放资源:清理几何体和材质
- 细节层次(LOD):为远处的物体使用LOD
React Three Fiber
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
- 声明式开发:使用R3F组件树,而非命令式代码
- Hooks使用:正确使用useFrame、useThree、useLoader
- 状态管理:使用Zustand管理全局3D状态
- 组件拆分:将场景拆分为可复用组件
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
- 热重载:使用HMR实现快速迭代
- 调试工具:使用drei的辅助工具和控制器
- 无障碍设计:为3D内容提供替代方案
- 多端测试:在多种设备和浏览器上测试
2. Decision Framework
2. 决策框架
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**项目范围是什么?
│
├─ **是否需要集成React?**
│ ├─ 是 → **React Three Fiber (R3F)**(90%的网页应用推荐使用)
│ └─ 否 → **原生Three.js**
│
├─ **是否对性能要求极高?**
│ ├─ 海量物体数量? → **InstancedMesh**
│ ├─ 复杂物理效果? → **Rapier (WASM)**
│ └─ 后期处理? → **EffectComposer / R3F Postprocessing**
│
└─ **视觉风格?**
├─ 写实风? → **PBR材质 + HDR灯光**
├─ 卡通风? → **卡通着色器 / 轮廓渲染通道**
└─ 抽象风? → **自定义GLSL着色器**Optimization Checklist (The 60FPS Rule)
优化检查清单(60FPS规则)
- Geometry: Use or
Dracocompression.Meshopt - Textures: Use or
.webp. Max size 2048x2048..ktx2 - 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 loop.
useFrame
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
- 几何体: 使用或
Draco压缩。Meshopt - 纹理: 使用或
.webp格式。最大尺寸为2048x2048。.ktx2 - 灯光: 尽可能烘焙灯光。最多保留1-2个实时阴影。
- 绘制调用: 合并几何体或使用实例化。
- 渲染循环: 避免在循环中创建对象。
useFrame
危险信号 → 升级至支持:
图形工程师- 浏览器中需要光线追踪(WebGPU实验性功能)
- 超出标准Three.js能力的自定义渲染管线
- 需要直接调用底层WebGL API
3. Core Workflows
3. 核心工作流
Workflow 1: React Three Fiber (R3F) Setup
工作流1:React Three Fiber (R3F) 搭建
Goal: A spinning cube with shadows and orbit controls.
Steps:
-
Setupbash
npm install three @types/three @react-three/fiber @react-three/drei -
Scene Component ()
Scene.tsxtsximport { 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> ); }
目标: 创建一个带阴影和轨道控制的旋转立方体。
步骤:
-
环境搭建bash
npm install three @types/three @react-three/fiber @react-three/drei -
场景组件()
Scene.tsxtsximport { 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
工作流3:模型加载与优化
Goal: Load a heavy GLTF model efficiently.
Steps:
-
Compression
- Use or
gltf-pipeline.gltf-transform - .
gltf-transform optimize input.glb output.glb --compress draco
- Use
-
Loading (R3F)tsx
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');
目标: 高效加载大型GLTF模型。
步骤:
-
压缩处理
- 使用或
gltf-pipeline工具。gltf-transform - 执行命令:。
gltf-transform optimize input.glb output.glb --compress draco
- 使用
-
R3F中加载模型tsx
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
5. 反模式与注意事项
❌ Anti-Pattern 1: Creating Objects in Loop
❌ 反模式1:在循环中创建对象
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(...))
表现:
useFrame(() => { new THREE.Vector3(...) })
问题:
- 垃圾回收(GC)导致卡顿。
- 60fps要求每帧耗时16ms,内存分配会严重影响性能。
正确做法:
- 复用全局/模块级变量。
const vec = new THREE.Vector3(); useFrame(() => vec.set(...))
❌ Anti-Pattern 2: Huge Textures
❌ 反模式2:超大纹理
What it looks like:
- Loading 4k textures (10MB each) for a background object.
.png
Why it fails:
- Slow load time.
- GPU memory exhaustion (mobile crash).
Correct approach:
- Use or
1ktextures.2k - Use for color maps,
.jpgonly if alpha needed..png - Use Basis/KTX2 for GPU compression.
表现:
- 为背景对象加载4k尺寸的纹理(每个10MB)。
.png
问题:
- 加载速度慢。
- 耗尽GPU内存(导致移动设备崩溃)。
正确做法:
- 使用1k或2k尺寸的纹理。
- 颜色贴图使用,仅在需要透明通道时使用
.jpg。.png - 使用Basis/KTX2格式进行GPU压缩。
❌ Anti-Pattern 3: Too Many Lights
❌ 反模式3:过多灯光
What it looks like:
- 50 dynamic PointLights.
Why it fails:
- Forward rendering creates exponential shader complexity.
Correct approach:
- Bake Lighting (Lightmaps) in Blender.
- Use + 1
AmbientLight(Sun).DirectionalLight
表现:
- 使用50个动态点光源。
问题:
- 前向渲染会导致着色器复杂度呈指数级增长。
正确做法:
- 烘焙灯光(在Blender中生成光照贴图)。
- 使用+ 1个
AmbientLight(模拟太阳光)。DirectionalLight
7. Quality Checklist
7. 质量检查清单
Performance:
- FPS: Stable 60fps on average laptop.
- Draw Calls: < 100 ideally.
- Memory: Geometries/Materials disposed when unmounted.
Visuals:
- Shadows: Soft shadows configured (ContactShadows or PCSS).
- Antialiasing: Enabled (default in R3F) or SMAA via post-proc.
- Responsiveness: Canvas resizes correctly on window resize.
Code:
- Declarative: Used R3F component tree, not imperative .
scene.add() - Optimization: used for expensive calculations.
useMemo
性能:
- 帧率: 在普通笔记本电脑上稳定保持60fps。
- 绘制调用: 理想情况下少于100次。
- 内存: 组件卸载时释放几何体/材质资源。
视觉效果:
- 阴影: 配置软阴影(ContactShadows或PCSS)。
- 抗锯齿: 已启用(R3F默认支持)或通过后期处理使用SMAA。
- 响应式: 画布可随窗口大小调整自动适配。
代码:
- 声明式: 使用R3F组件树,而非命令式的。
scene.add() - 优化: 对耗时计算使用。
useMemo
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
- 过多绘制调用: 独立几何体数量过多 - 尽可能合并几何体
- 内存泄漏: 未释放几何体/材质资源 - 始终在useEffect清理函数中执行清理操作
- 未优化纹理: 纹理文件过大 - 压缩并使用合适的格式
- 繁重计算: 阻塞主线程 - 卸载到Web Worker中执行
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
- 命令式代码: 在React中使用命令式Three.js代码 - 采用声明式R3F模式
- Prop透传: 多层级传递属性 - 使用上下文和状态存储
- 状态分散: 状态管理分散 - 使用集中式状态管理(Zustand)
- 组件臃肿: 单个组件过大 - 拆分为职责单一的组件
3D Modeling Anti-Patterns
3D建模类反模式
- 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
- 高多边形模型: 未优化的模型几何体 - 使用LOD和减面处理
- 缩放不统一: 模型缩放单位不一致 - 统一模型缩放比例
- 缺少碰撞体: 无碰撞几何体 - 添加不可见碰撞体以支持交互
- 灯光设置不当: 灯光数量过多 - 使用烘焙灯光和光照探针
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
- 无渐进式加载: 大型场景加载缓慢 - 实现加载状态
- 无降级方案: 未做优雅降级处理 - 提供替代体验
- 忽略无障碍: 3D内容无无障碍支持 - 添加替代内容
- 无性能预算: 未设定性能目标 - 制定并监控性能预算