在学习Three.js和WebGL的时,突发奇想我是不是用这个东西来加载3D模型呢,这样多酷炫呀,通过自己的研究发现居然是可以的!!!
下面,理论成立,实践开始!!请随着我脚步走进Three.js世界…
技术栈:Three.js + Vue3
编译平台:VsCode
总体思路
1-4 和 7 Three.js前期准备
5 导入模型(重点!)
6 模型显示是否好看的关键(重点!)
- 创建场景
- 创建相机
- 创建渲染器
- 添加控制器
- 添加模型
- 添加灯光
- 开始渲染
项目文件包
1、创建场景
2、创建相机
3、创建渲染器
4、添加控制器
5、添加模型
6、添加灯光
7、开始渲染
完整代码
<template>
<div class="canvas-container" ref="screenDom"></div>
</template>
<script setup>
import * as THREE from "three";
import { ref, onMounted, onUnmounted } from "vue";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { Reflector } from "three/examples/jsm/objects/Reflector";
let screenDom = ref(null);
onMounted(() => {
// 创建场景
let scene = new THREE.Scene();
// 创建相机
let camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(0, 2, 2);
scene.add(camera);
// 创建渲染器
let renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
screenDom.value.appendChild(renderer.domElement);
// 添加控制器
let controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
// 添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// 添加模型
let dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("./draco/gltf/");
dracoLoader.setDecoderConfig({ type: "js" });
let gltfLoader = new GLTFLoader();
gltfLoader.setDRACOLoader(dracoLoader);
gltfLoader.load("./assets/办公楼150.gltf", (gltf) => {
gltf.scene.scale.set(0.1, 0.1, 0.1);
gltf.scene.position.set(0, 0, 0);
scene.add(gltf.scene);
});
// 开始渲染
function render() {
controls.update();
renderer.render(scene,camera);
requestAnimationFrame(render);
}
render();
// 添加灯光
let light1 = new THREE.DirectionalLight(0xffffff, 1);
light1.position.set(0, 0, 1);
scene.add(light1);
let light2 = new THREE.DirectionalLight(0xffffff, 0.5);
light2.position.set(0, 1, 0);
scene.add(light2);
let light3 = new THREE.DirectionalLight(0xffffff, 0.5);
light3.position.set(1, 0, 0);
scene.add(light3);
// 聚光灯
let spotLight = new THREE.SpotLight(0xffffff, 1.5);
spotLight.position.set(5,5,5);
scene.add(spotLight);
});
</script>
<style scoped>
* {
margin: 0;
padding: 0;
}
body{
background-color: white;
}
.canvas-container {
width: 100vw;
height: 100vh;
}
</style>
最终效果