three-scene-component
v1.1.1
Published
A modular Three.js scene component with model loading, camera controls, click events, and smooth camera animations.
Maintainers
Readme
Three Scene Component
一个模块化的 Three.js 场景组件,提供模型加载、相机控制、点击事件、动画管理等丰富功能。
✨ 主要特性
- 🎯 模块化设计 - 清晰的架构,易于扩展和维护
- 📦 模型加载 - 支持 GLTF/GLB、OBJ、FBX 格式
- 🎮 相机控制 - 平滑飞行动画、自动适配物体
- 👆 交互事件 - 灵活的射线检测和事件系统
- 💡 灯光管理 - 多种光源类型的便捷创建和控制
- 🎨 纹理管理 - 纹理加载、缓存和应用
- 🎬 动画管理 - 模型骨骼动画播放控制
- 🔷 基础图形 - 丰富的几何体创建(立方体、球体、圆锥、圆环、胶囊等)
- 🔍 对象选择 - 多种方式查找和过滤场景对象
- 📊 状态记录 - 记录和导出对象状态
- 🛠️ 工具函数 - 实用的数学计算和辅助功能
- 🎛️ GUI 控制 - 集成 lil-gui 可视化控制面板
📦 安装
npm install three-scene-component🚀 快速开始
基础使用
import ThreeScene, { THREE, Helpers } from 'three-scene-component';
// 创建场景
const scene = new ThreeScene('container', {
backgroundColor: 0x111122,
gridHelper: true,
axesHelper: true,
});⚠️ 版本要求
重要: 本项目需要 Three.js r137+ 以支持所有几何体类型(特别是 CapsuleGeometry)。
- package.json 依赖:
three@^0.183.0 - Demo 文件使用:
[email protected] - 最低兼容版本:
[email protected]
const cube = scene.addCube({
position: { x: 0, y: 1, z: 0 },
color: 0xff0000,
name: 'myCube'
});
// 添加点击事件
scene.onClick((intersects) => {
if (intersects.length > 0) {
console.log('点击了:', intersects[0].object.name);
}
});加载模型
scene.loadModel('/models/character.glb', 'character')
.then((model) => {
console.log('模型加载完成');
// 设置动画
scene.setupAnimations(model);
scene.playAnimation('walk', { loop: true });
});灯光管理
// 添加环境光
scene.addAmbientLight({
color: 0xffffff,
intensity: 0.5,
name: 'ambient'
});
// 添加平行光
scene.addDirectionalLight({
color: 0xffffff,
intensity: 1,
position: { x: 5, y: 10, z: 5 },
castShadow: true,
name: 'sun'
});
// 动态调整灯光
scene.setLightIntensity('sun', 2);
scene.setLightColor('sun', 0xffaa00);纹理管理
// 加载纹理
const texture = await scene.loadTexture('/textures/wood.jpg', 'wood');
// 创建 Canvas 纹理
const canvasTex = scene.createCanvasTexture({
width: 256,
height: 256,
name: 'gradient',
draw: (ctx, w, h) => {
const grad = ctx.createLinearGradient(0, 0, w, h);
grad.addColorStop(0, '#ff0000');
grad.addColorStop(1, '#0000ff');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, w, h);
}
});
// 应用纹理到材质
scene.applyTexture(mesh.material, 'wood', 'map');动画控制
// 为模型设置动画
scene.setupAnimations(model);
// 播放动画
scene.playAnimation('run', {
loop: true,
timeScale: 1.5,
fadeInDuration: 0.5
});
// 暂停/恢复/停止
scene.pauseAnimation();
scene.resumeAnimation();
scene.stopAnimation();
// 获取可用动画列表
const animations = scene.getAvailableAnimations();
console.log(animations);对象选择
// 按名称查找
const obj = scene.getObjectByName('myCube');
// 按正则表达式查找
const objects = scene.getObjectsByRegex(/cube_\d+/);
// 按类型查找
const meshes = scene.getAllMeshes();
const lights = scene.getAllLights();
// 按标签查找
obj.userData.tags = ['interactive', 'selectable'];
const interactive = scene.getObjectsByTag('interactive');
// 自定义过滤
const visible = scene.getVisibleObjects();
const filtered = scene.getObjectsByFilter(obj => obj.position.y > 0);工具函数
import { Helpers } from 'three-scene-component';
// 距离计算
const dist = Helpers.distance(point1, point2);
// 角度计算
const angle = Helpers.angleDegrees(from, to);
// 获取包围盒信息
const center = Helpers.getBoundingBoxCenter(object);
const size = Helpers.getBoundingBoxSize(object);
// 缓动动画
Helpers.moveTo(object, targetPosition, 1000, () => {
console.log('移动完成');
});
// 随机数
const random = Helpers.random(0, 100);
const randomInt = Helpers.randomInt(1, 10);
// 防抖和节流
const debouncedFn = Helpers.debounce(myFunction, 300);
const throttledFn = Helpers.throttle(myFunction, 1000);📚 API 参考
ThreeScene 类
构造函数
new ThreeScene(container, options)参数:
container: HTMLElement 或元素 IDoptions: 配置对象backgroundColor: 背景颜色 (默认: 0x111122)cameraPosition: 相机初始位置 (默认: {x:5, y:5, z:10})gridHelper: 显示网格 (默认: true)axesHelper: 显示坐标轴 (默认: true)ambientLight: 启用环境光 (默认: true)directionalLight: 启用平行光 (默认: true)autoFitCamera: 加载模型后自动适配相机 (默认: true)
核心方法
模型加载
loadModel(url, name, onProgress)- 加载模型getObjectByName(name)- 根据名称获取对象
几何体创建
addCube(options)- 创建立方体addSphere(options)- 创建球体addCylinder(options)- 创建圆柱体addPlane(options)- 创建平面addCone(options)- 创建圆锥体 ⭐新增addTorus(options)- 创建圆环体 ⭐新增addCapsule(options)- 创建胶囊体 ⭐新增addDodecahedron(options)- 创建十二面体 ⭐新增addIcosahedron(options)- 创建二十面体 ⭐新增
相机控制
setView(position, target)- 瞬间设置视角flyTo(position, target, duration)- 平滑飞行到目标fitCameraToObject(object, offsetFactor, viewDirection)- 适配物体
事件处理
addEventListener(type, callback, target)- 添加事件监听removeEventListener(type, callback, target)- 移除事件监听onClick(callback, target)- 便捷点击事件
灯光管理 ⭐新增
addAmbientLight(options)- 添加环境光addDirectionalLight(options)- 添加平行光addPointLight(options)- 添加点光源addSpotLight(options)- 添加聚光灯addHemisphereLight(options)- 添加半球光setLightIntensity(name, intensity)- 设置灯光强度setLightColor(name, color)- 设置灯光颜色
纹理管理 ⭐新增
loadTexture(url, name)- 加载纹理getTexture(name)- 获取纹理applyTexture(material, textureName, mapType)- 应用纹理createCanvasTexture(options)- 创建 Canvas 纹理
动画管理 ⭐新增
setupAnimations(model)- 设置模型动画playAnimation(name, options)- 播放动画pauseAnimation()- 暂停动画resumeAnimation()- 恢复动画stopAnimation()- 停止动画getAvailableAnimations()- 获取可用动画列表
对象选择 ⭐增强
getObjectsByRegex(pattern, root)- 正则匹配getObjectsByGroup(groupName, root)- 按组查找getObjectsByFilter(filterFn, root)- 自定义过滤getObjectsByType(typeName, root)- 按类型查找 ⭐新增getAllMeshes(root)- 获取所有 Mesh ⭐新增getAllLights(root)- 获取所有光源 ⭐新增getObjectsByTag(tag, root)- 按标签查找 ⭐新增getVisibleObjects(root)- 获取可见对象 ⭐新增getInvisibleObjects(root)- 获取不可见对象 ⭐新增getObjectsByDepth(depth, root)- 按深度查找 ⭐新增
GUI 控制
createGUI(options)- 创建 GUIaddModelGUIControls(model, folderName, options)- 添加模型控制
状态记录
recordState(name, targets, options)- 记录状态getStateRecords()- 获取所有记录clearStateRecords()- 清空记录exportStateJSON(pretty)- 导出 JSONdownloadStateSnapshot(filename)- 下载快照
Helpers 工具类
import { Helpers } from 'three-scene-component';数学计算:
distance(point1, point2)- 计算距离angle(from, to)- 计算角度(弧度)angleDegrees(from, to)- 计算角度(度数)radToDeg(radians)- 弧度转度数degToRad(degrees)- 度数转弧度lerp(start, end, t)- 线性插值clamp(value, min, max)- 限制范围random(min, max)- 随机数randomInt(min, max)- 随机整数
几何操作:
getBoundingBoxCenter(object)- 获取包围盒中心getBoundingBoxSize(object)- 获取包围盒尺寸isPointInBoundingBox(point, object)- 检查点是否在包围盒内moveTo(object, targetPosition, duration, onComplete)- 移动对象
实用函数:
formatFileSize(bytes)- 格式化文件大小deepClone(obj)- 深克隆debounce(func, delay)- 防抖throttle(func, limit)- 节流generateId()- 生成唯一 ID
🎯 使用示例
查看 demo 文件夹中的完整示例:
test1.html- 基础功能演示test2.html- 状态记录演示test3-enhanced.html- 增强功能演示 ⭐
🔧 开发
# 安装依赖
npm install
# 构建
npm run build📝 更新日志
v1.1.0 (当前版本)
修复:
- ✅ 修复 ModelLoader 资源泄漏问题
- ✅ 修复 BaseScene 拼写错误
新增:
- ✅ AnimationManager - 模型动画管理
- ✅ LightingManager - 灯光管理
- ✅ TextureManager - 纹理管理
- ✅ Helpers - 实用工具函数
增强:
- ✅ SelectionManager - 新增多种对象查找方法
- ✅ PrimitiveFactory - 新增 5 种几何体类型
- ✅ 完善 TypeScript 类型定义
- ✅ 优化代码注释和文档
📄 许可证
ISC
👤 作者
ZJJ
享受 3D 开发的乐趣! 🎉
