1. 什么是欧拉角?
欧拉角是描述三维空间中物体旋转的三种角度表示方法,在三维图形学中,欧拉角通过三个独立旋转分量描述物体方向:
- - X轴(俯仰角 Pitch)
- - Y轴(偏航角 Yaw)
- - Z轴(滚转角 Roll)
在 Three.js 中,欧拉角通过 THREE.Euler
对象来实现。通过设置欧拉角的三个值,你可以控制物体在三维空间中的旋转。
2. 环境准备
# 创建Vue3项目
npm create vue@latest
cd your-project# 安装依赖
npm install three @types/three
3. 创建基本的 3D 场景
<script setup>
import { onMounted, ref } from 'vue'
import * as THREE from 'three'const container = ref(null)onMounted(() => {// 场景初始化const scene = new THREE.Scene()const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000)// 渲器配置const renderer = new THREE.WebGLRenderer({ antialias: true })renderer.setSize(window.innerWidth, window.innerHeight)container.value.appendChild(renderer.domElement)// 添加坐标轴辅助const axesHelper = new THREE.AxesHelper(5)scene.add(axesHelper)
})
</script><template><div ref="container"></div>
</template>
4. 使用欧拉角旋转物体
// 在组件中添加以下方法
function animate() {requestAnimationFrame(animate)// 获取立方体对象(需先创建)cube.rotation.x += 0.01 // X轴旋转(弧度)cube.rotation.y += 0.01 // Y轴旋转renderer.render(scene, camera)
}// 创建立方体示例
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
5. 完整代码
<script setup>
import { onMounted, ref } from 'vue'
import * as THREE from 'three'const container = ref(null)onMounted(() => {// ...(前文场景初始化代码)// 添加控制器(可选)const gui = new dat.GUI()gui.add(cube.rotation, 'x', 0, Math.PI*2)gui.add(cube.rotation, 'y', 0, Math.PI*2)
})function animate() {// ...(动画循环代码)
}
</script><style scoped>
canvas { width: 100%; height: 100vh; }
</style>
6. 进阶技巧
- 角度单位转换:
THREE.MathUtils.degToRad(180)
实现度数转弧度 - 旋转顺序控制:通过Matrix4.setEulerFromQuaternion()指定XYZ/ZYX等顺序
- 可视化调试:添加gizmo辅助工具显示当前旋转轴向