項目新需求,要在頁面中顯示已做好的3D模型比搭,做過技術(shù)調(diào)研后選擇了Threejs三維引擎。demo基本都是獨立頁面的,自己搞了一下身诺,在vue項目中完美運行了蜜托。分享一下
資源引入
npm i three-js
組件內(nèi)使用
引入:
import * as THREE from "three"; //引入Threejs
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
首先,創(chuàng)建初始化方法:
init() {
this.scene = new THREE.Scene();
this.scene.add(new THREE.AmbientLight(0x404040, 6)); //環(huán)境光
this.light = new THREE.DirectionalLight(0xdfebff, 0.45); //從正上方(不是位置)照射過來的平行光霉赡,0.45的強度
this.light.position.set(50, 200, 100);
this.light.position.multiplyScalar(0.3);
this.scene.add(this.light);
/**
* 相機設(shè)置
*/
let container = document.getElementById("threeContainer");//顯示3D模型的容器
this.camera = new THREE.PerspectiveCamera(
70,
container.clientWidth / container.clientHeight,
0.01,
10
);
this.camera.position.z = 1;
/**
* 創(chuàng)建渲染器對象
*/
this.renderer = new THREE.WebGLRenderer({ alpha: true });
this.renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(this.renderer.domElement);
//創(chuàng)建控件對象
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
}
外部模型加載函數(shù):
loadGltf() {
let self = this;
let loader = new GLTFLoader();
//load一個測試模型路徑:public/model/zhuozi2.gltf
loader.load("/model/zhuozi2.gltf", function(gltf) {
self.isLoading = false;//關(guān)閉載入中效果
self.mesh = gltf.scene;
self.mesh.scale.set(0.4, 0.4, 0.4);//設(shè)置大小比例
self.mesh.position.set(0, 0, 0);//設(shè)置位置
self.scene.add(self.mesh); // 將模型引入three橄务、
self.animate();
});
}
動畫效果:
animate() {
if (this.mesh) {
requestAnimationFrame(this.animate);
// this.mesh.rotation.x += 0.01;
this.mesh.rotation.y += 0.004;
this.renderer.render(this.scene, this.camera);
}
}