threejs-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseThree.js Builder Skill
Three.js 构建工具技能
Operator Context
操作上下文
This skill operates as an operator for Three.js web application creation, configuring Claude's behavior for structured, scene-graph-driven 3D development. It implements the Phased Construction architectural pattern -- Design, Build, Animate, Polish -- with Domain Intelligence embedded in modern Three.js (r150+) ES module patterns.
本技能作为Three.js网页应用创建的操作规范,为Claude配置了结构化、场景图驱动的3D开发行为。它实现了分阶段构建架构模式——设计、构建、动画、优化,并融入了现代Three.js(r150+)ES模块模式的领域智能。
Hardcoded Behaviors (Always Apply)
硬编码行为(始终适用)
- CLAUDE.md Compliance: Read and follow repository CLAUDE.md before building
- Over-Engineering Prevention: Build only what the user asked for. No speculative features, no "while I'm here" additions
- ES Modules Only: Always use modern ES module imports from CDN or npm. Never use legacy global variable or CommonJS
THREE - Scene Graph First: Structure all objects through the scene graph hierarchy. Use for logical groupings
Group - Responsive by Default: Every app must handle window resize and cap at 2
devicePixelRatio - Single HTML File: Default output is one self-contained HTML file unless user specifies otherwise
- CLAUDE.md 合规性:构建前阅读并遵循仓库中的CLAUDE.md
- 防止过度设计:仅构建用户要求的内容,不添加推测性功能或“顺便”增加的功能
- 仅使用ES模块:始终使用来自CDN或npm的现代ES模块导入。绝不使用遗留全局变量或CommonJS
THREE - 优先场景图:通过场景图层次结构组织所有对象。使用进行逻辑分组
Group - 默认响应式:每个应用必须处理窗口大小调整,并将限制为2
devicePixelRatio - 单HTML文件:默认输出为一个自包含的HTML文件,除非用户另有指定
Default Behaviors (ON unless disabled)
默认行为(默认开启,可关闭)
- Three-Point Lighting: Set up ambient + directional + fill light for standard scenes
- OrbitControls: Include orbit camera controls for interactive scenes
- Animation Loop via setAnimationLoop: Use over manual
renderer.setAnimationLoop()requestAnimationFrame - Configuration Object: Define visual constants (colors, speeds, sizes) in a top-level object
CONFIG - Modular Setup Functions: Separate scene creation into ,
createScene(),createLights()functionscreateMeshes()
- 三点照明:为标准场景设置环境光+平行光+补光
- OrbitControls:为交互式场景添加轨道相机控制
- 通过setAnimationLoop实现动画循环:使用替代手动
renderer.setAnimationLoop()requestAnimationFrame - 配置对象:在顶层对象中定义视觉常量(颜色、速度、尺寸)
CONFIG - 模块化设置函数:将场景创建拆分为、
createScene()、createLights()等函数createMeshes()
Optional Behaviors (OFF unless enabled)
可选行为(默认关闭,可开启)
- Post-Processing: Bloom, depth of field via EffectComposer
- Model Loading: GLTF/GLB loading with auto-center and scale
- Custom Shaders: ShaderMaterial with GLSL vertex/fragment shaders
- Shadow Mapping: PCFSoft shadows with configurable map resolution
- Physics Integration: Cannon.js gravity and collision simulation
- Raycasting: Mouse/touch picking of 3D objects
- 后期处理:通过EffectComposer实现 bloom、景深效果
- 模型加载:GLTF/GLB模型加载,支持自动居中与缩放
- 自定义着色器:使用GLSL顶点/片段着色器的ShaderMaterial
- 阴影映射:可配置分辨率的PCFSoft阴影
- 物理集成:Cannon.js重力与碰撞模拟
- 射线检测:3D对象的鼠标/触摸拾取
What This Skill CAN Do
本技能可实现的功能
- Create complete Three.js web applications from a user description
- Set up scenes with proper lighting, camera, renderer, and resize handling
- Use built-in geometries (Box, Sphere, Cylinder, Torus, Plane, Cone, Icosahedron)
- Apply PBR materials (Standard, Physical) and basic materials (Basic, Phong, Normal)
- Implement animations: rotation, oscillation, wave motion, mouse tracking
- Add OrbitControls, GLTF model loading, post-processing, raycasting
- Vary visual style to match context (portfolio, game, data viz, background effect)
- 根据用户描述创建完整的Three.js网页应用
- 搭建包含合适照明、相机、渲染器和大小调整处理的场景
- 使用内置几何体(立方体、球体、圆柱体、圆环、平面、圆锥体、二十面体)
- 应用PBR材质(Standard、Physical)和基础材质(Basic、Phong、Normal)
- 实现动画:旋转、摆动、波浪运动、鼠标追踪
- 添加OrbitControls、GLTF模型加载、后期处理、射线检测
- 根据场景(作品集、游戏、数据可视化、背景效果)调整视觉风格
What This Skill CANNOT Do
本技能无法实现的功能
- Create complex game engines (use Unity, Unreal instead)
- Generate or edit 3D model files (modeling is done in Blender, etc.)
- Implement VR/AR experiences (specialized WebXR knowledge needed)
- Replace dedicated CAD software for engineering drawings
- Optimize scenes with 1M+ polygons (requires specialized LOD/culling strategies)
- 创建复杂游戏引擎(请使用Unity、Unreal)
- 生成或编辑3D模型文件(建模需使用Blender等工具)
- 实现VR/AR体验(需要专业WebXR知识)
- 替代专用CAD软件进行工程绘图
- 优化包含100万+多边形的场景(需要专业LOD/剔除策略)
Instructions
操作步骤
Phase 1: DESIGN
阶段1:设计
Goal: Understand what the user wants and select appropriate Three.js components.
Step 1: Identify the core visual element
Determine from the user request:
- What is the primary 3D content? (geometric shapes, loaded model, particles, terrain)
- What interaction is needed? (none, orbit, click, mouse tracking)
- What animation brings it to life? (rotation, oscillation, morphing, physics)
- What is the context? (portfolio, game, data viz, background, product viewer)
Step 2: Select components
markdown
undefined目标:理解用户需求并选择合适的Three.js组件。
步骤1:识别核心视觉元素
从用户请求中确定:
- 主要3D内容是什么?(几何形状、加载的模型、粒子、地形)
- 需要什么交互?(无、轨道控制、点击、鼠标追踪)
- 用什么动画赋予场景生命力?(旋转、摆动、变形、物理模拟)
- 应用场景是什么?(作品集、游戏、数据可视化、背景、产品查看器)
步骤2:选择组件
markdown
undefinedScene Plan
场景规划
- Geometry: [primitives or model loading]
- Material: [Basic/Standard/Physical/Shader]
- Lighting: [ambient + directional + fill / custom]
- Animation: [rotation / wave / mouse / physics]
- Controls: [OrbitControls / none / custom]
- Extras: [post-processing / raycasting / particles]
**Step 3: Choose visual style based on context**
| Context | Style Guidance |
|---------|---------------|
| Portfolio/showcase | Elegant, smooth animations, muted palette |
| Game/interactive | Bright colors, snappy controls, particle effects |
| Data visualization | Clean lines, grid helpers, clear labels |
| Background effect | Subtle, slow movement, dark gradients |
| Product viewer | Realistic PBR lighting, smooth orbit, neutral backdrop |
**Gate**: Scene plan documented with geometry, material, lighting, animation, and controls selected. Proceed only when gate passes.- 几何体:[基础几何体或模型加载]
- 材质:[Basic/Standard/Physical/Shader]
- 照明:[环境光+平行光+补光 / 自定义]
- 动画:[旋转 / 波浪 / 鼠标交互 / 物理模拟]
- 控制:[OrbitControls / 无 / 自定义]
- 附加功能:[后期处理 / 射线检测 / 粒子效果]
**步骤3:根据场景选择视觉风格**
| 场景 | 风格指南 |
|---------|---------------|
| 作品集/展示 | 优雅、流畅的动画,柔和色调 |
| 游戏/交互式 | 明亮色彩、灵敏控制、粒子效果 |
| 数据可视化 | 简洁线条、网格辅助、清晰标签 |
| 背景效果 | 柔和、缓慢运动、深色渐变 |
| 产品查看器 | 真实PBR照明、流畅轨道控制、中性背景 |
**检查点**:已记录包含几何体、材质、照明、动画和控制的场景规划。仅当检查通过后才可进入下一阶段。Phase 2: BUILD
阶段2:构建
Goal: Construct the scene with proper structure and modern patterns.
Step 1: Create HTML boilerplate
Every app starts with this structure:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[App Title]</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; background: #000; }
canvas { display: block; }
</style>
</head>
<body>
<script type="module">
import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';
// Additional imports as needed
</script>
</body>
</html>Step 2: Build scene infrastructure
javascript
// Scene, camera, renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75, window.innerWidth / window.innerHeight, 0.1, 1000
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);
// Resize handler (always include)
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});Step 3: Add lighting, geometry, and materials per scene plan
Build each component from the Phase 1 plan. Create geometry once, reuse where possible. Use for hierarchical transforms.
GroupGate: Scene renders without errors. All planned geometry, materials, and lights are present. Proceed only when gate passes.
目标:使用恰当结构和现代模式构建场景。
步骤1:创建HTML模板
每个应用都以此结构开始:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[应用标题]</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; background: #000; }
canvas { display: block; }
</style>
</head>
<body>
<script type="module">
import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';
// 按需添加其他导入
</script>
</body>
</html>步骤2:搭建场景基础设施
javascript
// 场景、相机、渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75, window.innerWidth / window.innerHeight, 0.1, 1000
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);
// 大小调整处理(必须包含)
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});步骤3:根据场景规划添加照明、几何体和材质
根据阶段1的规划构建每个组件。几何体仅创建一次,按需复用。使用进行层级变换。
Group检查点:场景可无错误渲染。所有规划的几何体、材质和灯光均已存在。仅当检查通过后才可进入下一阶段。
Phase 3: ANIMATE
阶段3:动画
Goal: Add motion, interaction, and life to the scene.
Step 1: Set up animation loop
javascript
renderer.setAnimationLoop((time) => {
// Update animations
// Update controls if present
renderer.render(scene, camera);
});Step 2: Implement planned animations
Apply transforms per frame. Use parameter (milliseconds) for time-based animation. Multiply by small factors (0.001, 0.0005) for smooth motion.
timeStep 3: Add interaction handlers
Wire up mouse/touch events, orbit controls, or raycasting per the scene plan.
Gate: Animations run smoothly. Interactions respond correctly. No console errors. Proceed only when gate passes.
目标:为场景添加运动、交互和生命力。
步骤1:设置动画循环
javascript
renderer.setAnimationLoop((time) => {
// 更新动画
// 若有控制则更新控制
renderer.render(scene, camera);
});步骤2:实现规划的动画
逐帧应用变换。使用参数(毫秒)实现基于时间的动画。乘以小系数(0.001、0.0005)以获得平滑运动。
time步骤3:添加交互处理程序
根据场景规划连接鼠标/触摸事件、轨道控制或射线检测。
检查点:动画流畅运行。交互响应正确。无控制台错误。仅当检查通过后才可进入下一阶段。
Phase 4: POLISH
阶段4:优化
Goal: Ensure quality, performance, and completeness.
Step 1: Verify responsive behavior
- Resize browser window -- canvas fills viewport without distortion
- capped at 2
devicePixelRatio
Step 2: Verify visual quality
- Lighting produces visible surfaces (no black screen from missing lights)
- Materials look correct (metalness/roughness values appropriate)
- Colors and style match the intended context
Step 3: Test the output
- Open the HTML file in a browser or serve it locally
- Confirm no console errors or warnings
- Confirm animations and interactions work as intended
Step 4: Clean up
- Remove any debug helpers (AxesHelper, GridHelper, Stats) unless user wanted them
- Ensure no commented-out code or TODO markers remain
Gate: All verification steps pass. Output is complete and ready to deliver.
目标:确保质量、性能和完整性。
步骤1:验证响应式行为
- 调整浏览器窗口——画布无扭曲地填充视口
- 已限制为2
devicePixelRatio
步骤2:验证视觉质量
- 照明可照亮表面(无因缺少灯光导致的黑屏)
- 材质显示正确(金属度/粗糙度值合适)
- 颜色和风格符合预期场景
步骤3:测试输出
- 在浏览器中打开HTML文件或本地运行
- 确认无控制台错误或警告
- 确认动画和交互按预期工作
步骤4:清理
- 移除所有调试辅助工具(AxesHelper、GridHelper、Stats),除非用户需要
- 确保无注释代码或TODO标记残留
检查点:所有验证步骤通过。输出完整且可交付。
Examples
示例
Example 1: Simple Animated Scene
示例1:简单动画场景
User says: "Create a threejs scene with a rotating icosahedron"
Actions:
- Design: low-poly icosahedron, standard material, three-point lighting, continuous rotation (DESIGN)
- Build: HTML boilerplate, scene setup, IcosahedronGeometry with flatShading, lighting (BUILD)
- Animate: rotation on x and y axes using time parameter (ANIMATE)
- Polish: verify resize, test in browser, remove debug helpers (POLISH) Result: Single HTML file with responsive, animated 3D scene
用户需求:“创建一个带有旋转二十面体的Three.js场景”
操作:
- 设计:低多边形二十面体、标准材质、三点照明、持续旋转(设计阶段)
- 构建:HTML模板、场景设置、带flatShading的IcosahedronGeometry、照明(构建阶段)
- 动画:使用time参数实现x和y轴旋转(动画阶段)
- 优化:验证大小调整、浏览器测试、移除调试工具(优化阶段) 结果:单个响应式动画3D场景的HTML文件
Example 2: Interactive Product Viewer
示例2:交互式产品查看器
User says: "Build a 3D product viewer that loads a GLB model"
Actions:
- Design: GLTF loader, PBR material, realistic lighting, OrbitControls, neutral backdrop (DESIGN)
- Build: HTML with GLTFLoader import, auto-center/scale model, environment lighting (BUILD)
- Animate: orbit controls with damping, optional auto-rotate (ANIMATE)
- Polish: loading progress indicator, responsive, verify model renders (POLISH) Result: Interactive model viewer with orbit controls and proper lighting
用户需求:“构建一个可加载GLB模型的3D产品查看器”
操作:
- 设计:GLTF加载器、PBR材质、真实感照明、OrbitControls、中性背景(设计阶段)
- 构建:包含GLTFLoader导入的HTML、自动居中/缩放模型、环境照明(构建阶段)
- 动画:带阻尼的轨道控制、可选自动旋转(动画阶段)
- 优化:加载进度指示器、响应式、验证模型渲染(优化阶段) 结果:带有轨道控制和合适照明的交互式模型查看器
Error Handling
错误处理
Error: "Black Screen / Nothing Renders"
错误:“黑屏/无内容渲染”
Cause: Missing lights (StandardMaterial requires light), object not added to scene, or camera pointing wrong direction
Solution:
- Verify at least one light is added to the scene (AmbientLight + DirectionalLight)
- Confirm all meshes are added with
scene.add(mesh) - Check camera position -- as baseline
camera.position.z = 5 - If using BasicMaterial or NormalMaterial, lights are not the issue -- check geometry and camera
原因:缺少灯光(StandardMaterial需要灯光)、对象未添加到场景、相机指向错误方向
解决方案:
- 验证至少有一个灯光添加到场景(AmbientLight + DirectionalLight)
- 确认所有网格通过添加
scene.add(mesh) - 检查相机位置——基线设置为
camera.position.z = 5 - 若使用BasicMaterial或NormalMaterial,灯光不是问题——检查几何体和相机
Error: "OrbitControls is not defined"
错误:“OrbitControls未定义”
Cause: Incorrect import path or missing import statement
Solution:
- For CDN:
import { OrbitControls } from 'https://unpkg.com/three@0.160.0/examples/jsm/controls/OrbitControls.js' - For npm:
import { OrbitControls } from 'three/addons/controls/OrbitControls.js' - Never use -- addons are not on the THREE namespace in modern Three.js
THREE.OrbitControls
原因:导入路径错误或缺少导入语句
解决方案:
- CDN方式:
import { OrbitControls } from 'https://unpkg.com/three@0.160.0/examples/jsm/controls/OrbitControls.js' - npm方式:
import { OrbitControls } from 'three/addons/controls/OrbitControls.js' - 绝不要使用——在现代Three.js中,插件不在THREE命名空间下
THREE.OrbitControls
Error: "Model Loads But Is Invisible or Tiny"
错误:“模型加载但不可见或极小”
Cause: Model scale/position does not match scene scale, or model is centered at wrong origin
Solution:
- Compute bounding box:
new THREE.Box3().setFromObject(gltf.scene) - Center the model:
gltf.scene.position.sub(box.getCenter(new THREE.Vector3())) - Scale camera distance:
camera.position.z = Math.max(size.x, size.y, size.z) * 2
原因:模型缩放/位置与场景比例不匹配,或模型原点居中错误
解决方案:
- 计算边界框:
new THREE.Box3().setFromObject(gltf.scene) - 居中模型:
gltf.scene.position.sub(box.getCenter(new THREE.Vector3())) - 调整相机距离:
camera.position.z = Math.max(size.x, size.y, size.z) * 2
Anti-Patterns
反模式
Anti-Pattern 1: Creating Geometry Inside the Animation Loop
反模式1:在动画循环内创建几何体
What it looks like: called every frame
Why wrong: Allocates memory every frame, causes GC pauses and frame rate collapse
Do instead: Create all geometries and materials once during setup. Transform only position, rotation, and scale in the loop.
new THREE.BoxGeometry(1,1,1)表现:每帧调用
危害:每帧分配内存,导致GC停顿和帧率骤降
正确做法:在设置阶段一次性创建所有几何体和材质。仅在循环中变换位置、旋转和缩放。
new THREE.BoxGeometry(1,1,1)Anti-Pattern 2: Using Legacy Global THREE Patterns
反模式2:使用遗留全局THREE模式
What it looks like: with
Why wrong: CommonJS/global patterns are deprecated. CDN bundles are outdated. Addons like OrbitControls are not available on the global namespace.
Do instead: Always use with ES module imports from unpkg or npm.
<script src="three.js">var scene = new THREE.Scene()<script type="module">表现:使用并通过创建场景
危害:CommonJS/全局模式已被弃用。CDN包已过时。OrbitControls等插件不在全局命名空间中。
正确做法:始终使用,从unpkg或npm导入ES模块。
<script src="three.js">var scene = new THREE.Scene()<script type="module">Anti-Pattern 3: Skipping Pixel Ratio Cap
反模式3:未限制像素比
What it looks like: without cap
Why wrong: Retina/HiDPI displays (3x, 4x) render at extreme resolutions, destroying performance on mobile
Do instead:
renderer.setPixelRatio(window.devicePixelRatio)renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))表现:未加限制
危害:Retina/HiDPI显示器(3x、4x)会以极高分辨率渲染,严重影响移动端性能
正确做法:
renderer.setPixelRatio(window.devicePixelRatio)renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))Anti-Pattern 4: Hardcoding Everything With No Configuration
反模式4:无配置的硬编码
What it looks like: Magic numbers scattered throughout -- , ,
Why wrong: Impossible to tweak, experiment, or understand intent
Do instead: Define a object at the top with named constants: , ,
0x44aa880.00175CONFIGCONFIG.colorCONFIG.rotationSpeedCONFIG.fov表现:代码中散布魔法数字——、、
危害:无法调整、实验或理解意图
正确做法:在顶层定义对象,包含命名常量:、、
0x44aa880.00175CONFIGCONFIG.colorCONFIG.rotationSpeedCONFIG.fovAnti-Pattern 5: Identical Output Every Time
反模式5:每次输出完全相同
What it looks like: Every scene uses green cube, camera at z=5, directional light at (1,1,1)
Why wrong: Produces generic, cookie-cutter results that ignore the user's context
Do instead: Vary geometry, color palette, camera angle, lighting setup, and animation style based on the scene's purpose (see Phase 1 style guidance).
表现:每个场景都使用绿色立方体、相机z=5、平行光位于(1,1,1)
危害:生成通用、千篇一律的结果,忽略用户场景
正确做法:根据场景用途(见阶段1风格指南)调整几何体、调色板、相机角度、照明设置和动画风格。
References
参考
This skill uses these shared patterns:
- Anti-Rationalization - Prevents shortcut rationalizations
- Verification Checklist - Pre-completion checks
本技能使用以下共享模式:
- 反合理化 - 防止捷径合理化
- 验证清单 - 完成前检查
Domain-Specific Anti-Rationalization
领域特定反合理化
| Rationalization | Why It's Wrong | Required Action |
|---|---|---|
| "It renders, must be done" | Rendering does not mean correct lighting, animation, or interaction | Complete Phase 4 verification |
| "I'll skip OrbitControls, simpler" | User expects interactive scenes by default | Include controls unless explicitly static |
| "BasicMaterial is fine" | BasicMaterial ignores lighting, looks flat and cheap | Use StandardMaterial unless unlit effect is intentional |
| "Resize handler isn't needed" | Scene breaks on any window change, looks broken on mobile | Always include resize handling |
| 合理化借口 | 错误原因 | 要求操作 |
|---|---|---|
| “能渲染就完成了” | 渲染不代表照明、动画或交互正确 | 完成阶段4验证 |
| “我跳过OrbitControls,更简单” | 用户默认期望交互式场景 | 除非明确要求静态,否则包含控制 |
| “BasicMaterial足够了” | BasicMaterial忽略照明,看起来平淡廉价 | 除非需要无光照效果,否则使用StandardMaterial |
| “不需要大小调整处理” | 场景在窗口变化时失效,在移动端显示异常 | 始终包含大小调整处理 |
Reference Files
参考文件
- : GLTF loading, post-processing, shaders, raycasting, physics, InstancedMesh, TypeScript support
${CLAUDE_SKILL_DIR}/references/advanced-topics.md
- :GLTF加载、后期处理、着色器、射线检测、物理、InstancedMesh、TypeScript支持
${CLAUDE_SKILL_DIR}/references/advanced-topics.md