three-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Three.js Best Practices

Three.js 最佳实践

Comprehensive performance optimization guide for Three.js applications. Contains 120+ rules across 18 categories, prioritized by impact.
这是一份针对Three.js应用的全面性能优化指南,包含18个分类下的120+条规则,按影响优先级排序。

Sources & Credits

来源与致谢

This skill compiles best practices from multiple authoritative sources:
  • Official guidelines from Three.js
    llms
    branch maintained by mrdoob
  • 100 Three.js Tips by Utsubo - Excellent comprehensive guide covering WebGPU, asset optimization, and performance tips
本指南整合了多个权威来源的最佳实践:
  • mrdoob维护的Three.js
    llms
    分支官方指南
  • Utsubo发布的《100个Three.js技巧》(100 Three.js Tips)——涵盖WebGPU、资源优化和性能技巧的优质综合指南

When to Apply

适用场景

Reference these guidelines when:
  • Setting up a new Three.js project
  • Writing or reviewing Three.js code
  • Optimizing performance or fixing memory leaks
  • Working with custom shaders (GLSL or TSL)
  • Implementing WebGPU features
  • Building VR/AR experiences with WebXR
  • Integrating physics engines
  • Optimizing for mobile devices
在以下场景中可参考本指南:
  • 搭建新的Three.js项目时
  • 编写或评审Three.js代码时
  • 优化性能或修复内存泄漏时
  • 处理自定义着色器(GLSL或TSL)时
  • 实现WebGPU功能时
  • 构建WebXR相关的VR/AR体验时
  • 集成物理引擎时
  • 针对移动设备进行优化时

Rule Categories by Priority

按优先级排序的规则分类

PriorityCategoryImpactPrefix
0Modern Setup & ImportsFUNDAMENTAL
setup-
1Memory Management & DisposeCRITICAL
memory-
2Render Loop OptimizationCRITICAL
render-
3Draw Call OptimizationCRITICAL
drawcall-
4Geometry & Buffer ManagementHIGH
geometry-
5Material & Texture OptimizationHIGH
material-
6Asset CompressionHIGH
asset-
7Lighting & ShadowsMEDIUM-HIGH
lighting-
8Scene Graph OrganizationMEDIUM
scene-
9Shader Best Practices (GLSL)MEDIUM
shader-
10TSL (Three.js Shading Language)MEDIUM
tsl-
11WebGPU RendererMEDIUM
webgpu-
12Loading & AssetsMEDIUM
loading-
13Core Web VitalsMEDIUM-HIGH
vitals-
14Camera & ControlsLOW-MEDIUM
camera-
15Animation SystemMEDIUM
animation-
16Physics IntegrationMEDIUM
physics-
17WebXR / VR / ARMEDIUM
webxr-
18AudioLOW-MEDIUM
audio-
19Post-ProcessingMEDIUM
postpro-
20Mobile OptimizationHIGH
mobile-
21ProductionHIGH
error-
,
migration-
22Debug & DevToolsLOW
debug-
优先级分类影响等级前缀
0现代项目配置与导入基础核心
setup-
1内存管理与资源释放至关重要
memory-
2渲染循环优化至关重要
render-
3绘制调用优化至关重要
drawcall-
4几何体与缓冲区管理高影响
geometry-
5材质与纹理优化高影响
material-
6资源压缩高影响
asset-
7光照与阴影中高影响
lighting-
8场景图组织中影响
scene-
9GLSL着色器最佳实践中影响
shader-
10TSL(Three.js着色语言)中影响
tsl-
11WebGPU渲染器中影响
webgpu-
12加载与资源管理中影响
loading-
13Web核心指标中高影响
vitals-
14相机与控制器中低影响
camera-
15动画系统中影响
animation-
16物理引擎集成中影响
physics-
17WebXR / VR / AR中影响
webxr-
18音频中低影响
audio-
19后期处理中影响
postpro-
20移动端优化高影响
mobile-
21生产环境部署高影响
error-
,
migration-
22调试与开发工具低影响
debug-

Quick Reference

快速参考

0. Modern Setup (FUNDAMENTAL)

0. 现代项目配置(基础核心)

  • setup-use-import-maps
    - Use Import Maps, not old CDN scripts
  • setup-choose-renderer
    - WebGLRenderer (default) vs WebGPURenderer (TSL/compute)
  • setup-animation-loop
    - Use
    renderer.setAnimationLoop()
    not manual RAF
  • setup-basic-scene-template
    - Complete modern scene template
  • setup-use-import-maps
    - 使用Import Maps,而非旧版CDN脚本
  • setup-choose-renderer
    - WebGLRenderer(默认)与WebGPURenderer(TSL/计算场景)的选择
  • setup-animation-loop
    - 使用
    renderer.setAnimationLoop()
    而非手动RAF
  • setup-basic-scene-template
    - 完整的现代场景模板

1. Memory Management (CRITICAL)

1. 内存管理(至关重要)

  • memory-dispose-geometry
    - Always dispose geometries
  • memory-dispose-material
    - Always dispose materials and textures
  • memory-dispose-textures
    - Dispose dynamically created textures
  • memory-dispose-render-targets
    - Always dispose WebGLRenderTarget
  • memory-dispose-recursive
    - Use recursive disposal for hierarchies
  • memory-dispose-on-unmount
    - Dispose in React cleanup/unmount
  • memory-renderer-dispose
    - Dispose renderer when destroying view
  • memory-reuse-objects
    - Reuse geometries and materials
  • memory-dispose-geometry
    - 务必释放几何体资源
  • memory-dispose-material
    - 务必释放材质与纹理资源
  • memory-dispose-textures
    - 释放动态创建的纹理
  • memory-dispose-render-targets
    - 务必释放WebGLRenderTarget
  • memory-dispose-recursive
    - 对层级结构使用递归释放
  • memory-dispose-on-unmount
    - 在React的清理/卸载阶段释放资源
  • memory-renderer-dispose
    - 销毁视图时释放渲染器
  • memory-reuse-objects
    - 复用几何体与材质

2. Render Loop (CRITICAL)

2. 渲染循环(至关重要)

  • render-single-raf
    - Single requestAnimationFrame loop
  • render-conditional
    - Render on demand for static scenes
  • render-delta-time
    - Use delta time for animations
  • render-avoid-allocations
    - Never allocate in render loop
  • render-cache-computations
    - Cache expensive computations
  • render-frustum-culling
    - Enable frustum culling
  • render-update-matrix-manual
    - Disable auto matrix updates for static objects
  • render-pixel-ratio
    - Limit pixel ratio to 2
  • render-antialias-wisely
    - Use antialiasing judiciously
  • render-single-raf
    - 单个requestAnimationFrame循环
  • render-conditional
    - 静态场景按需渲染
  • render-delta-time
    - 使用deltaTime处理动画
  • render-avoid-allocations
    - 绝不在渲染循环中分配内存
  • render-cache-computations
    - 缓存耗时计算结果
  • render-frustum-culling
    - 启用视锥体剔除
  • render-update-matrix-manual
    - 禁用静态对象的自动矩阵更新
  • render-pixel-ratio
    - 将像素比限制为2
  • render-antialias-wisely
    - 谨慎使用抗锯齿

3. Draw Call Optimization (CRITICAL)

3. 绘制调用优化(至关重要)

  • draw-call-optimization
    - Target under 100 draw calls per frame
  • geometry-instanced-mesh
    - Use InstancedMesh for identical objects
  • geometry-batched-mesh
    - Use BatchedMesh for varied geometries (same material)
  • geometry-merge-static
    - Merge static geometries with BufferGeometryUtils
  • draw-call-optimization
    - 目标是每帧绘制调用低于100次
  • geometry-instanced-mesh
    - 对相同对象使用InstancedMesh
  • geometry-batched-mesh
    - 对不同几何体(相同材质)使用BatchedMesh
  • geometry-merge-static
    - 使用BufferGeometryUtils合并静态几何体

4. Geometry (HIGH)

4. 几何体(高影响)

  • geometry-buffer-geometry
    - Always use BufferGeometry
  • geometry-merge-static
    - Merge static geometries
  • geometry-instanced-mesh
    - Use InstancedMesh for identical objects
  • geometry-lod
    - Use Level of Detail for complex models
  • geometry-index-buffer
    - Use indexed geometry
  • geometry-vertex-count
    - Minimize vertex count
  • geometry-attributes-typed
    - Use appropriate typed arrays
  • geometry-interleaved
    - Consider interleaved buffers
  • geometry-buffer-geometry
    - 始终使用BufferGeometry
  • geometry-merge-static
    - 合并静态几何体
  • geometry-instanced-mesh
    - 对相同对象使用InstancedMesh
  • geometry-lod
    - 为复杂模型使用LOD(细节层次)
  • geometry-index-buffer
    - 使用索引几何体
  • geometry-vertex-count
    - 最小化顶点数量
  • geometry-attributes-typed
    - 使用合适的类型数组
  • geometry-interleaved
    - 考虑使用交错缓冲区

5. Materials & Textures (HIGH)

5. 材质与纹理(高影响)

  • material-reuse
    - Reuse materials across meshes
  • material-simplest-sufficient
    - Use simplest material that works
  • material-texture-size-power-of-two
    - Power-of-two texture dimensions
  • material-texture-compression
    - Use compressed textures (KTX2/Basis)
  • material-texture-mipmaps
    - Enable mipmaps appropriately
  • material-texture-anisotropy
    - Use anisotropic filtering for floors
  • material-texture-atlas
    - Use texture atlases
  • material-avoid-transparency
    - Minimize transparent materials
  • material-onbeforecompile
    - Use onBeforeCompile for shader mods (or TSL)
  • material-reuse
    - 在多个网格间复用材质
  • material-simplest-sufficient
    - 使用满足需求的最简材质
  • material-texture-size-power-of-two
    - 纹理尺寸使用2的幂次
  • material-texture-compression
    - 使用压缩纹理(KTX2/Basis)
  • material-texture-mipmaps
    - 合理启用mipmaps
  • material-texture-anisotropy
    - 为地面使用各向异性过滤
  • material-texture-atlas
    - 使用纹理图集
  • material-avoid-transparency
    - 尽量减少透明材质
  • material-onbeforecompile
    - 使用onBeforeCompile修改着色器(或使用TSL)

6. Asset Compression (HIGH)

6. 资源压缩(高影响)

  • asset-compression
    - Draco, Meshopt, KTX2 compression guide
  • asset-draco
    - 90-95% geometry size reduction
  • asset-ktx2
    - GPU-compressed textures (UASTC vs ETC1S)
  • asset-meshopt
    - Alternative to Draco with faster decompression
  • asset-lod
    - Level of Detail for 30-40% frame rate improvement
  • asset-compression
    - Draco、Meshopt、KTX2压缩指南
  • asset-draco
    - 几何体尺寸减少90-95%
  • asset-ktx2
    - GPU压缩纹理(UASTC vs ETC1S)
  • asset-meshopt
    - Draco的替代方案,解压速度更快
  • asset-lod
    - LOD(细节层次)可提升30-40%帧率

7. Lighting & Shadows (MEDIUM-HIGH)

7. 光照与阴影(中高影响)

  • lighting-limit-lights
    - Limit to 3 or fewer active lights
  • lighting-shadows-advanced
    - PointLight cost, CSM, fake shadows
  • lighting-bake-static
    - Bake lighting for static scenes
  • lighting-shadow-camera-tight
    - Fit shadow camera tightly
  • lighting-shadow-map-size
    - Choose appropriate shadow resolution (512-4096)
  • lighting-shadow-selective
    - Enable shadows selectively
  • lighting-shadow-cascade
    - Use CSM for large scenes
  • lighting-shadow-auto-update
    - Disable autoUpdate for static scenes
  • lighting-probe
    - Use Light Probes
  • lighting-environment
    - Environment maps for ambient light
  • lighting-fake-shadows
    - Gradient planes for budget contact shadows
  • lighting-limit-lights
    - 限制活跃灯光数量为3个或更少
  • lighting-shadows-advanced
    - 点光源开销、CSM、模拟阴影
  • lighting-bake-static
    - 为静态场景烘焙光照
  • lighting-shadow-camera-tight
    - 紧密贴合阴影相机范围
  • lighting-shadow-map-size
    - 选择合适的阴影分辨率(512-4096)
  • lighting-shadow-selective
    - 选择性启用阴影
  • lighting-shadow-cascade
    - 大型场景使用CSM(级联阴影贴图)
  • lighting-shadow-auto-update
    - 静态场景禁用自动更新
  • lighting-probe
    - 使用光照探针
  • lighting-environment
    - 使用环境贴图实现环境光
  • lighting-fake-shadows
    - 使用渐变平面实现低成本接触阴影

8. Scene Graph (MEDIUM)

8. 场景图(中影响)

  • scene-group-objects
    - Use Groups for organization
  • scene-layers
    - Use Layers for selective rendering
  • scene-visible-toggle
    - Use visible flag, not add/remove
  • scene-flatten-static
    - Flatten static hierarchies
  • scene-name-objects
    - Name objects for debugging
  • object-pooling
    - Reuse objects instead of create/destroy
  • scene-group-objects
    - 使用Group组织对象
  • scene-layers
    - 使用Layers实现选择性渲染
  • scene-visible-toggle
    - 使用visible属性切换显示,而非添加/移除对象
  • scene-flatten-static
    - 扁平化静态层级结构
  • scene-name-objects
    - 为对象命名以便调试
  • object-pooling
    - 复用对象而非创建/销毁

9. Shaders GLSL (MEDIUM)

9. GLSL着色器(中影响)

  • shader-precision
    - Use mediump for mobile (~2x faster)
  • shader-mobile
    - Mobile-specific optimizations (varyings, branching)
  • shader-avoid-branching
    - Replace conditionals with mix/step
  • shader-precompute-cpu
    - Precompute on CPU
  • shader-avoid-discard
    - Avoid discard, use alphaTest
  • shader-texture-lod
    - Use textureLod for known mip levels
  • shader-uniform-arrays
    - Prefer uniform arrays
  • shader-varying-interpolation
    - Limit varyings to 3 for mobile
  • shader-pack-data
    - Pack data into RGBA channels
  • shader-chunk-injection
    - Use Three.js shader chunks
  • shader-precision
    - 移动端使用mediump(速度提升约2倍)
  • shader-mobile
    - 移动端特定优化(varyings、分支)
  • shader-avoid-branching
    - 使用mix/step替代条件判断
  • shader-precompute-cpu
    - 在CPU端预计算
  • shader-avoid-discard
    - 避免使用discard,改用alphaTest
  • shader-texture-lod
    - 已知mip级别时使用textureLod
  • shader-uniform-arrays
    - 优先使用uniform数组
  • shader-varying-interpolation
    - 移动端限制varyings数量为3个
  • shader-pack-data
    - 将数据打包到RGBA通道
  • shader-chunk-injection
    - 使用Three.js着色器片段

10. TSL - Three.js Shading Language (MEDIUM)

10. TSL - Three.js着色语言(中影响)

  • tsl-why-use
    - Use TSL instead of onBeforeCompile
  • tsl-setup-webgpu
    - WebGPU setup for TSL
  • tsl-complete-reference
    - Full TSL type system and functions
  • tsl-material-slots
    - Material node properties reference
  • tsl-node-materials
    - Use NodeMaterial classes
  • tsl-basic-operations
    - Types, operations, swizzling
  • tsl-functions
    - Creating TSL functions with Fn()
  • tsl-conditionals
    - If, select, loops in TSL
  • tsl-textures
    - Textures and triplanar mapping
  • tsl-noise
    - Built-in noise functions (mx_noise_float, mx_fractal_noise)
  • tsl-post-processing
    - bloom, blur, dof, ao
  • tsl-compute-shaders
    - GPGPU and compute operations
  • tsl-glsl-to-tsl
    - GLSL to TSL translation
  • tsl-why-use
    - 使用TSL替代onBeforeCompile
  • tsl-setup-webgpu
    - 为TSL配置WebGPU
  • tsl-complete-reference
    - 完整的TSL类型系统与函数
  • tsl-material-slots
    - 材质节点属性参考
  • tsl-node-materials
    - 使用NodeMaterial类
  • tsl-basic-operations
    - 类型、操作、分量选择
  • tsl-functions
    - 使用Fn()创建TSL函数
  • tsl-conditionals
    - TSL中的if、select、循环
  • tsl-textures
    - 纹理与三平面映射
  • tsl-noise
    - 内置噪声函数(mx_noise_float、mx_fractal_noise)
  • tsl-post-processing
    - bloom、模糊、景深、环境光遮蔽
  • tsl-compute-shaders
    - GPGPU与计算操作
  • tsl-glsl-to-tsl
    - GLSL到TSL的转换

11. WebGPU Renderer (MEDIUM)

11. WebGPU渲染器(中影响)

  • webgpu-renderer
    - Setup, browser support, migration guide
  • webgpu-render-async
    - Use renderAsync for compute-heavy scenes
  • webgpu-feature-detection
    - Check adapter features
  • webgpu-instanced-array
    - GPU-persistent buffers
  • webgpu-storage-textures
    - Read-write compute textures
  • webgpu-workgroup-memory
    - Shared memory (10-100x faster)
  • webgpu-indirect-draws
    - GPU-driven rendering
  • webgpu-renderer
    - 配置、浏览器支持、迁移指南
  • webgpu-render-async
    - 计算密集型场景使用renderAsync
  • webgpu-feature-detection
    - 检查适配器特性
  • webgpu-instanced-array
    - GPU持久化缓冲区
  • webgpu-storage-textures
    - 可读写计算纹理
  • webgpu-workgroup-memory
    - 共享内存(速度提升10-100倍)
  • webgpu-indirect-draws
    - 驱动GPU渲染

12. Loading & Assets (MEDIUM)

12. 加载与资源(中影响)

  • loading-draco-compression
    - Use Draco for large meshes
  • loading-gltf-preferred
    - Use glTF format
  • gltf-loading-optimization
    - Full loader setup with DRACO/Meshopt/KTX2
  • loading-progress-feedback
    - Show loading progress
  • loading-async-await
    - Use async/await for loading
  • loading-lazy
    - Lazy load non-critical assets
  • loading-cache-assets
    - Enable caching
  • loading-dispose-unused
    - Unload unused assets
  • loading-draco-compression
    - 大型网格使用Draco
  • loading-gltf-preferred
    - 使用glTF格式
  • gltf-loading-optimization
    - 配置支持DRACO/Meshopt/KTX2的完整加载器
  • loading-progress-feedback
    - 显示加载进度
  • loading-async-await
    - 使用async/await处理加载
  • loading-lazy
    - 懒加载非关键资源
  • loading-cache-assets
    - 启用缓存
  • loading-dispose-unused
    - 卸载未使用资源

13. Core Web Vitals (MEDIUM-HIGH)

13. Web核心指标(中高影响)

  • core-web-vitals
    - LCP, FID, CLS optimization for 3D
  • vitals-lazy-load
    - Lazy load 3D below the fold with IntersectionObserver
  • vitals-code-split
    - Dynamic import Three.js modules
  • vitals-preload
    - Preload critical assets with link tags
  • vitals-progressive-loading
    - Low-res to high-res progressive load
  • vitals-placeholders
    - Show placeholder geometry during load
  • vitals-web-workers
    - Offload heavy work to workers
  • vitals-streaming
    - Stream large scenes by chunks
  • core-web-vitals
    - 3D场景下的LCP、FID、CLS优化
  • vitals-lazy-load
    - 使用IntersectionObserver懒加载视口下方的3D内容
  • vitals-code-split
    - 动态导入Three.js模块
  • vitals-preload
    - 使用link标签预加载关键资源
  • vitals-progressive-loading
    - 从低分辨率到高分辨率渐进式加载
  • vitals-placeholders
    - 加载时显示占位几何体
  • vitals-web-workers
    - 将繁重工作卸载到Web Worker
  • vitals-streaming
    - 分块流式加载大型场景

14. Camera & Controls (LOW-MEDIUM)

14. 相机与控制器(中低影响)

  • camera-near-far
    - Set tight near/far planes
  • camera-fov
    - Choose appropriate FOV
  • camera-controls-damping
    - Use damping for smooth controls
  • camera-resize-handler
    - Handle resize properly
  • camera-orbit-limits
    - Set orbit control limits
  • camera-near-far
    - 设置紧凑的近/远裁剪面
  • camera-fov
    - 选择合适的视场角
  • camera-controls-damping
    - 使用阻尼实现平滑控制器
  • camera-resize-handler
    - 正确处理窗口大小变化
  • camera-orbit-limits
    - 设置轨道控制器限制

15. Animation (MEDIUM)

15. 动画(中影响)

  • animation-system
    - AnimationMixer, blending, morph targets, skeletal
  • animation-system
    - AnimationMixer、混合、 morph targets、骨骼动画

16. Physics (MEDIUM)

16. 物理引擎(中影响)

  • physics-integration
    - Rapier, Cannon-es integration patterns
  • physics-compute-shaders
    - GPU physics with compute shaders
  • physics-integration
    - Rapier、Cannon-es集成模式
  • physics-compute-shaders
    - 使用计算着色器实现GPU物理

17. WebXR (MEDIUM)

17. WebXR(中影响)

  • webxr-setup
    - VR/AR buttons, controllers, hit testing
  • webxr-setup
    - VR/AR按钮、控制器、命中测试

18. Audio (LOW-MEDIUM)

18. 音频(中低影响)

  • audio-spatial
    - PositionalAudio, HRTF, spatial sound
  • audio-spatial
    - PositionalAudio、HRTF、空间音频

19. Post-Processing (MEDIUM)

19. 后期处理(中影响)

  • postprocessing-optimization
    - pmndrs/postprocessing guide
  • postpro-renderer-config
    - Disable AA, stencil, depth for post
  • postpro-merge-effects
    - Combine effects in single pass
  • postpro-selective-bloom
    - Selective bloom for performance
  • postpro-resolution-scaling
    - Half resolution for 2x FPS
  • postpro-webgpu-native
    - TSL-based post for WebGPU
  • postprocessing-optimization
    - pmndrs/postprocessing指南
  • postpro-renderer-config
    - 后期处理时禁用AA、模板、深度
  • postpro-merge-effects
    - 单通道合并多个效果
  • postpro-selective-bloom
    - 选择性 bloom 以提升性能
  • postpro-resolution-scaling
    - 半分辨率可提升2倍FPS
  • postpro-webgpu-native
    - 基于TSL的WebGPU后期处理

20. Optimization (HIGH)

20. 移动端优化(高影响)

  • mobile-optimization
    - Mobile-specific optimizations and checklist
  • raycasting-optimization
    - BVH, layers, GPU picking
  • mobile-optimization
    - 移动端特定优化与检查清单
  • raycasting-optimization
    - BVH、Layers、GPU拾取

21. Production (HIGH)

21. 生产环境(高影响)

  • error-handling-recovery
    - WebGL context loss and recovery
  • migration-checklist
    - Breaking changes by version
  • error-handling-recovery
    - WebGL上下文丢失与恢复
  • migration-checklist
    - 各版本的破坏性变更

22. Debug & DevTools (LOW)

22. 调试与开发工具(低影响)

  • debug-devtools
    - Complete debugging toolkit
  • debug-stats-gl
    - stats-gl for WebGL/WebGPU monitoring
  • debug-lil-gui
    - lil-gui for live parameter tweaking
  • debug-spector
    - Spector.js for WebGL frame capture
  • debug-renderer-info
    - Monitor draw calls and memory
  • debug-three-mesh-bvh
    - Fast raycasting with BVH
  • debug-context-lost
    - Handle WebGL context loss
  • debug-animation-loop-profiling
    - Profile render loop sections
  • debug-conditional
    - Remove debug code in production
  • debug-devtools
    - 完整的调试工具集
  • debug-stats-gl
    - 使用stats-gl监控WebGL/WebGPU
  • debug-lil-gui
    - 使用lil-gui实时调整参数
  • debug-spector
    - 使用Spector.js捕获WebGL帧
  • debug-renderer-info
    - 监控绘制调用与内存
  • debug-three-mesh-bvh
    - 使用BVH实现快速射线检测
  • debug-context-lost
    - 处理WebGL上下文丢失
  • debug-animation-loop-profiling
    - 分析渲染循环各部分性能
  • debug-conditional
    - 生产环境移除调试代码

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/setup-use-import-maps.md
rules/memory-dispose-geometry.md
rules/tsl-complete-reference.md
rules/mobile-optimization.md
Each rule file contains:
  • Brief explanation of why it matters
  • BAD code example with explanation
  • GOOD code example with explanation
  • Additional context and references
阅读单个规则文件获取详细说明与代码示例:
rules/setup-use-import-maps.md
rules/memory-dispose-geometry.md
rules/tsl-complete-reference.md
rules/mobile-optimization.md
每个规则文件包含:
  • 规则重要性的简要说明
  • 错误代码示例及解释
  • 正确代码示例及解释
  • 额外上下文与参考资料

Key Patterns

核心模式

Modern Import Maps

现代Import Maps

html
<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.182.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.182.0/examples/jsm/",
    "three/tsl": "https://cdn.jsdelivr.net/npm/three@0.182.0/build/three.tsl.js"
  }
}
</script>
html
<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.182.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.182.0/examples/jsm/",
    "three/tsl": "https://cdn.jsdelivr.net/npm/three@0.182.0/build/three.tsl.js"
  }
}
</script>

Proper Disposal

正确的资源释放

javascript
function disposeObject(obj) {
  if (obj.geometry) obj.geometry.dispose();
  if (obj.material) {
    if (Array.isArray(obj.material)) {
      obj.material.forEach(m => m.dispose());
    } else {
      obj.material.dispose();
    }
  }
}
javascript
function disposeObject(obj) {
  if (obj.geometry) obj.geometry.dispose();
  if (obj.material) {
    if (Array.isArray(obj.material)) {
      obj.material.forEach(m => m.dispose());
    } else {
      obj.material.dispose();
    }
  }
}

TSL Basic Usage

TSL基础用法

javascript
import { texture, uv, color, time, sin } from 'three/tsl';

const material = new THREE.MeshStandardNodeMaterial();
material.colorNode = texture(map).mul(color(0xff0000));
material.colorNode = color(0x00ff00).mul(sin(time).mul(0.5).add(0.5));
javascript
import { texture, uv, color, time, sin } from 'three/tsl';

const material = new THREE.MeshStandardNodeMaterial();
material.colorNode = texture(map).mul(color(0xff0000));
material.colorNode = color(0x00ff00).mul(sin(time).mul(0.5).add(0.5));

Mobile Detection

移动端检测

javascript
const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, isMobile ? 1.5 : 2));
javascript
const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, isMobile ? 1.5 : 2));