一、项目引入Three
安装three
yarn add three
npm install -S three
在需要展示模型中引入
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
二、初始化场景、相机、光照等
//属性
let scene;
const renderer = ref();
const camera = ref();
const controls = ref();
const animationId = ref();
const isShowProgress = ref(false);
const initThree = () => {
//场景
scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);
//环境光
scene.add(new THREE.AmbientLight('#ffffff'));
//灯光
const frontLight = new THREE.DirectionalLight(0xffffff, 1);
frontLight.position.set(0, 10, 0);
scene.add(frontLight);
const afterLight = new THREE.DirectionalLight(0xffffff, 1);
afterLight.position.set(0, -10, 0);
scene.add(afterLight);
//相机
camera.value = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.value.position.set(0, 50, 0);
camera.value.lookAt(0, 0, 0);
//render
const element = document.getElementById(props.id);
renderer.value = new THREE.WebGLRenderer({ antialias: false });
renderer.value.setPixelRatio(window.devicePixelRatio);
renderer.value.setSize(element.clientWidth, element.clientHeight);
renderer.value.setClearColor(0xcce9ff, 1);
element.appendChild(renderer.value.domElement);
//控制器
controls.value = new OrbitControls(camera.value, renderer.value.domElement);
let url = props.modelUrl + '';
if (IsLocationLop) {
url = url.replace('https://damei.jhznxx.com', '');
}
isShowProgress.value = true;
addModel();
initRender();
};
const initRender = () => {
animationId.value = requestAnimationFrame(initRender);
renderer.value.render(scene, camera.value);
};
//加载OBJ模型
const addModel = () =>{
new MTLLoader().setPath('/OBJ/Block/').load(
'Block.mtl',
(mtl) => {
mtl.preload();//模型材质
new OBJLoader().setMaterials(mtl).setPath('/OBJ/Block/').load(
'Block.obj',
(obj) => {
obj.children[0].geometry.computeBoundingBox();//
obj.children[0].geometry.center();//定位到模型中心
obj.rotateY(Math.PI);//模型倒置
scene.add(obj);
},
);
}
);
}
//加载GLTF模型
const addGltfModel = () =>{
let loader = new GLTFLoader();
loader.load('/gltf/car/scene.gltf', (gltf) => {
let mesh = gltf.scene.children[0];
if (mesh instanceof THREE.Object3D) {
scene.add(mesh);
} else {
console.log('格式不正确');
}
});
}
效果如下:
以上是记录three加载obj和gitf格式模型