npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

three-scene-component

v1.1.1

Published

A modular Three.js scene component with model loading, camera controls, click events, and smooth camera animations.

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)。

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 或元素 ID
  • options: 配置对象
    • 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) - 创建 GUI
  • addModelGUIControls(model, folderName, options) - 添加模型控制
状态记录
  • recordState(name, targets, options) - 记录状态
  • getStateRecords() - 获取所有记录
  • clearStateRecords() - 清空记录
  • exportStateJSON(pretty) - 导出 JSON
  • downloadStateSnapshot(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 开发的乐趣! 🎉