基础场景

依赖

1
pnpm install three @types/three three-stdlib

结构

1
2
3
4
5
6
7
src/
├── assets/
├── components/
│ └── ThreeScene.vue # 3D场景组件
├── views/
│ └── HomeView.vue # 主视图
└── main.js

基础 3D 场景

HomeView.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
<div class="home-view">
<ThreeScene />
</div>
</template>

<script setup>
import ThreeScene from '@/components/ThreeScene.vue'
</script>

<style>
.home-view {
position: relative;
height: 100vh;
}
</style>

ThreeScene.vue

1
<div ref="sceneContainer"></div>
1
const sceneContainer = ref(null) // 场景容器引用

初始化场景

1
2
3
4
5
6
7
8
9
10
const scene = new THREE.Scene() // 场景
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) // 相机
const renderer = new THREE.WebGLRenderer() // 渲染器

sceneContainer.value.appendChild(renderer.domElement) // 添加到DOM

const geometry = new THREE.BoxGeometry() // 几何体
const material = new THREE.MeshBasicMaterial({ color: 0x00FF00 }) // 材质
const cube = new THREE.Mesh(geometry, material) // 网络
scene.add(cube)