three.ez 库入门指南
three.ez 库入门指南
项目概述
three.ez 是一个专为简化 Three.js 开发而设计的工具库。该库封装了常用的交互功能,包括事件监听、元素拖拽、数据绑定、焦点控制、智能刷新以及动画过渡等特性,让开发者能够以更简洁的方式构建 Three.js 应用。通过抽象底层复杂性,three.ez 让开发者将更多精力投入到创意实现上。
环境配置与安装
包管理器安装方式
使用 npm 进行安装:
npm install @three.ez/main
CDN 引用方式
也可以通过 CDN 直接引入:
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.167.1/build/three.module.js",
"three/examples/jsm": "https://unpkg.com/three@0.167.1/examples/jsm/",
"@three.ez/main": "https://unpkg.com/@three.ez/main@0.5.5/index.js"
}
}
</script>
基础应用示例
下面展示了一个使用 three.ez 构建的简单 3D 场景:
import { Scene, Mesh, BoxGeometry, MeshNormalMaterial } from 'three';
import { Main, PerspectiveCameraAuto } from '@three.ez/main';
// 构造几何体对象
const cube = new Mesh(new BoxGeometry(), new MeshNormalMaterial());
cube.draggable = true; // 启用拖拽功能
// 绑定动画更新事件
cube.on('animate', (event) => {
cube.rotateX(event.delta);
cube.rotateY(event.delta * 2);
});
// 鼠标进入和离开事件处理
cube.on(['pointerover', 'pointerout'], (event) => {
const scaleValue = event.type === 'pointerover' ? 1.5 : 1;
cube.scale.setScalar(scaleValue);
});
// 构建场景并加入对象
const scene = new Scene();
scene.add(cube);
// 初始化主控制器
const engine = new Main();
engine.createView([
scene,
{
camera: new PerspectiveCameraAuto(70).translateZ(1)
}
]);
核心功能与应用场景
交互事件系统
该库提供了类似浏览器 DOM 的事件机制,方便为 3D 对象添加用户交互逻辑。例如添加点击响应:
cube.on('click', (event) => {
event.stopPropagation();
console.log('立方体被点击!');
});
拖拽操作支持
启用拖拽只需设置对应属性,并可监听拖拽过程:
cube.draggable = true;
cube.on('drag', (event) => {
console.log(`当前位置:${event.position}`);
});
性能优化渲染
通过智能渲染机制减少不必要的绘制操作,提升运行效率:
scene.activeSmartRendering();
cube.material.color.set('yellow');
cube.needsRender = true; // 强制刷新当前帧
相关技术生态
three.js
作为基础框架,three.ez 完全兼容并依赖于 Three.js。Three.js 是业界广泛使用的 WebGL 库,适用于游戏、可视化及创意编程等多个领域。
vite
在开发环境中推荐使用 Vite 工具链,其具备快速启动和热更新能力,有效提高开发效率。
troika-three-text
对于需要在 3D 场景中显示文字的应用,可集成 troika-three-text 实现高质量文本渲染。
结合这些工具和库,开发者能够更加高效地搭建丰富的 3D 交互式应用程序。