介绍
threejs 是一个基于 WebGL 的 3D 引擎,它可以在浏览器中创建 3D 场景,并且可以通过 JavaScript 来控制三维场景中的元素。由于官方文档访问较慢,建议访问:https://threejs.rocyuan.top。
注意:文章中所有的代码均使用 vue3 进行编写。
目录
threejs 源码目录主要结构如下:
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | three.js├── build
 ├── docs
 ├── examples
 │   ├── jsm
 ├── editor
 ├── manual
 ├── playground
 └── src
 
 | 
注意:扩展库的导入 three/addons/... 等价于 three/examples/jsm/... ;addons/* 是 examples/jsm/* 目录的导出别名。
安装引入
安装引入方式等问题官方文档写的已经很清楚了,就不赘述了。
文档:https://threejs.rocyuan.top/docs/#manual/zh/introduction/Installation
三要素
threejs 绘制 3d 图形的三要素:
- 场景(Scene):场景是一个容器,用于存储所有的物体和光源等。
- 相机(Camera):相机是一个虚拟的眼睛,用于观察场景中的一切物体。
- 渲染器(Renderer):渲染器是一个将场景渲染到屏幕上的工具。
建立三维场景
使用 threejs 三要素建立一个简单的三维场景。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 
 | <template><div ref="threeContainer" class="three-container"></div>
 </template>
 <script setup>
 import { ref, onMounted } from "vue";
 import * as THREE from "three";
 
 const threeContainer = ref(null);
 
 function init3D() {
 
 const scene = new THREE.Scene();
 
 const camera = new THREE.PerspectiveCamera(75, threeContainer.value.clientWidth / threeContainer.value.clientHeight, 0.1, 1000);
 
 const renderer = new THREE.WebGLRenderer();
 renderer.setSize(threeContainer.value.clientWidth, threeContainer.value.clientHeight);
 threeContainer.value.appendChild(renderer.domElement);
 
 
 function animate() {
 requestAnimationFrame(animate);
 renderer.render(scene, camera);
 }
 animate();
 }
 
 onMounted(() => {
 init3D();
 });
 </script>
 <style scoped>
 .three-container {
 width: 100vw;
 height: 100vh;
 }
 </style>
 
 | 
至此,三维场景已经建立完成,后续将详细介绍三要素中的 场景、相机、渲染器。