目录
九、源码地址(代码很多地方写的比较丑陋,可自行更改和封装,请嘴下留情谢谢)
一、模板和样式
<template>
<div class="container">
<div id="model"></div>
</div>
</template>
<style scoped>
.container {
width: 1920px;
height: 1080px;
position: relative;
background-color: rgb(83, 83, 83);
}
</style>
二、引入three.js库和组件
import * as THREE from "three";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
三、定义单文件名称和定义全局变量
这里的publicPath在加载模型时要用到
name: "ThreeModel",
data() {
return {
publicPath: process.env.BASE_URL,
mesh: null,
camera: null,
scene: null,
renderer: null,
carMovePath: null,
shperePathIndex: [1001, 666, 333],
meshArr: [],
};
},
四、创建场景、光源、相机、相机和根据浏览器窗口自适应
是否需要根据浏览器窗口自适应取决于个人
// 创建场景
createScene() {
this.scene = new THREE.Scene();
},
// 创建光源
createLight() {
// 环境光
const ambientLight = new THREE.AmbientLight(0x111111); // 创建环境光
this.scene.add(ambientLight); // 将环境光添加到场景
const directionLight = new THREE.DirectionalLight(0xffffff);
directionLight.position.set(-20, 30, 40);
directionLight.intensity = 1.5;
this.scene.add(directionLight);
},
// 创建相机
createCamera() {
this.camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
50000
);
this.camera.position.set(0, 700, 1000); // 设置相机位置
this.camera.lookAt(new THREE.Vector3(0, 0, 0)); // 设置相机方向
this.scene.add(this.camera);
},
//根据浏览器窗口自适应
onWindowResize() {
this.cssRender.setSize(window.innerWidth, window.innerHeight);
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
},
// 创建渲染器
createRender() {
this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
this.renderer.setSize(window.innerWidth, window.innerHeight); // 设置渲染区域尺寸
this.renderer.setClearColor(0x0