TresJS 简介
TresJS是一个基于Three.js
的Vue组件库,它让在Vue.js应用中创建3D场景
变得简单直观。TresJS的目标是简化3D开发,让你可以像使用普通Vue组件一样创建复杂的3D内容。
安装
首先,在你的Vue项目中安装TresJS:
npm install three @tresjs/core
如果你需要TypeScript支持,别忘了安装three.js的类型定义:
npm install @types/three -D
全局引入
import Tres from '@tresjs/core'
import { createApp } from 'vue'
import App from './App.vue'export const app = createApp(App)app.use(Tres)
app.mount('#app')
局部引入
<script setup lang="ts">
import { TresCanvas } from '@tresjs/core'
</script><template><TresCanvas><!-- Your scene here --></TresCanvas>
</template>
基本使用
1. 创建一个简单的场景
在你的Vue组件中:
<script setup>
import { TresCanvas } from '@tresjs/core'
</script><template><TresCanvas><TresPerspectiveCamera :position="[0, 0, 10]" /><TresAmbientLight :intensity="1" /><TresMesh><TresBoxGeometry :args="[2, 2, 2]" /><TresMeshStandardMaterial color="red" /></TresMesh></TresCanvas>
</template>
这个例子创建了一个包含红色立方体的简单场景。
2. 添加动画
<script setup>
import { TresCanvas } from '@tresjs/core'
import { ref, onMounted } from 'vue'
import * as THREE from 'three'
const cubeRef = ref(null)// 创建动画循环
function animate () {if (cubeRef.value) {cubeRef.value.rotation.x += 0.01cubeRef.value.rotation.y += 0.01}requestAnimationFrame(animate)
}onMounted(() => {// 启动动画animate()
})
</script><template><TresCanvas><TresPerspectiveCamera :position="[0, 0, 10]" /><TresAmbientLight :intensity="1" /><TresMesh ref="cubeRef"><TresBoxGeometry :args="[2, 2, 2]" /><TresMeshStandardMaterial color="blue" /></TresMesh></TresCanvas>
</template>
3. 使用加载器导入3D模型
npm install @tresjs/cientos
<script setup>
import { TresCanvas } from '@tresjs/core'
import { GLTFLoader } from '@tresjs/cientos'
</script><template><TresCanvas><TresPerspectiveCamera :position="[5, 5, 5]" /><TresAmbientLight :intensity="1" /><TresDirectionalLight :position="[10, 10, 5]" :intensity="1" /><GLTFLoader src="/path/to/your/model.glb" /></TresCanvas>
</template>
高级特性
TresJS还提供了许多高级功能,如:
- 物理引擎集成
- 后期处理效果
- 射线投射与交互
- 自定义着色器
学习资源
- TresJS官方文档
- TresJS GitHub仓库
- Three.js文档
- Vue.js文档
示例项目
尝试创建一个简单的交互式3D场景,用户可以旋转模型:
<script setup>
import { TresCanvas, useRenderLoop } from '@tresjs/core'
import { OrbitControls } from '@tresjs/cientos'
import { ref } from 'vue'const cubeRef = ref(null)useRenderLoop(() => {if (cubeRef.value) {cubeRef.value.rotation.x += 0.003}
})
</script><template><TresCanvas><TresPerspectiveCamera :position="[0, 0, 10]" /><OrbitControls /><TresAmbientLight :intensity="0.5" /><TresDirectionalLight :position="[10, 10, 10]" :intensity="1" /><TresMesh ref="cubeRef"><TresBoxGeometry :args="[3, 3, 3]" /><TresMeshStandardMaterial color="#42b883" /></TresMesh></TresCanvas>
</template>