效果图:
1、前期准备,了解three和tresjs的关系。
使用原始的Three.js 我们会需要创建一个 canvas
HTML 元素来挂载 WebglRenderer
并初始化一个场景。通过 TresJS 你仅仅需要导入默认组件 <TresCanvas />
并把它添加到你的 Vue 组件的模板部分即可。
TresJS 是用 Typescript 编写的,是完全类型化的。如果您使用的是 Typescript,您就能充分享受类型的好处。 只需要保证你安装了 three 的类型定义。
1. threejs文件包下载和目录简介 | Three.js中文网
2、实现过程,本项目在uniappx下实现,支持ts\vue3
2.1 创建项目后,通过命令行下载依赖
npm install three @tresjs/core @tresjs/cientos
cientos扩展包,包含了现成助手和组件的集合,这些助手和组件不属于核心包的一部分。如:轨道控件,加载模型,一些常用的形状等。(Cientos
2.2 创建index.uvue和UgglyBunny.uvue页面,代码直接参考官方代码即可。
参考代码:
模型地址:https://raw.githubusercontent.com/Tresjs/assets/main/models/gltf/ugly-naked-bunny/ugly-naked-bunny-animated.gltf
2.2.1 index.uvue
<script setup>
import { TresCanvas } from '@tresjs/core';
import { OrbitControls } from '@tresjs/cientos';
import { BasicShadowMap, SRGBColorSpace, NoToneMapping } from 'three'
import UgglyBunny from './UgglyBunny.uvue';
const gl = {
clearColor: '#F78B3D',
shadows: true,
alpha: false,
shadowMapType: BasicShadowMap,
outputColorSpace: SRGBColorSpace,
toneMapping: NoToneMapping,
windowSize: true,
}
</script>
<template>
<TresCanvas v-bind="gl">
<TresPerspectiveCamera
:position="[2, 2, 9]"
:look-at="[0, 2, 0]"
/>
<OrbitControls />
<Suspense>
<UgglyBunny />
</Suspense>
<TresDirectionalLight
color="#F78B3D"
:position="[3, 3, 3]"
:intensity="1"
/>
<TresAmbientLight :intensity="2" />
</TresCanvas>
</template>
2.2.2 UgglyBunny.uvue
<script setup lang="ts">
import { ref } from 'vue'
import { useAnimations, useGLTF } from '@tresjs/cientos'
const { scene: model, animations } = await useGLTF('../../public/models/ugly-naked-bunny-animated.gltf'
)
const { actions } = useAnimations(animations, model)
console.log(model,actions)
const currentAction = ref(actions.Greeting)//动作名字叫Greeting
currentAction.value.play()
</script>
<template>
<primitive :object="model" />
</template>
3、注意
3.1换成自己的动画模型的时候,注意动画的名称的更换actions.xx。
3.2 模型要异步请求,所以index.uvue中要用Suspense标签包裹模型组件,UgglyBunny.uvue需要用await请求
3.3 假如你自己使用的gltf文件是压缩文件,会报错Failed to load resource Error: THREE.GLTFLoader: No DRACOLoader instance provided.则需要添加使用,{draco:true}
const { scene: model, animations } = await useGLTF('xxxx.gltf',{draco:true}
)