安装three
npm intall three
组件
<template>
<div class='model'>
<img class="close"
:src="require(`@/assets/common/round_close.png`)"
@click="close" alt="">
<div class="fixcenter" id="modelbox"></div>
</div>
</template>
<script>
import * as Three from 'three';
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
var scene,camera,renderer,orbitControls;
export default {
name: 'model',
props: {
resource: {
type: Object,
default: {}
}
},
components:{
},
data(){
return {
}
},
watch: {
},
computed: {
},
mounted(){
this.initScene();
this.initModelContainer();
this.initCamera();
this.initRenderer();
this.initControls();
this.loadModel();
this.animate();
},
methods: {
close(){
cancelAnimationFrame(this.aId);
this.$parent.closePop();
},
initScene() {
scene = new Three.Scene();
scene.add(new Three.AmbientLight(0xffffff,1));
},
initModelContainer() {
this.model_container = document.getElementById("modelbox");
this.height = this.model_container.clientHeight;
this.width = this.model_container.clientWidth;
},
initCamera() {
camera = new Three.PerspectiveCamera(70, this.width / this.height, 0.01, 1000);
camera.position.set(0, 0, -5);
camera.lookAt(new Three.Vector3(0,0,0));
},
initRenderer() {
renderer = new Three.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(this.width, this.height);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.domElement.style.outline = "none";
this.model_container.appendChild(renderer.domElement);
},
animate(){
renderer.render(scene,camera);
orbitControls && orbitControls.update();
this.aId = requestAnimationFrame(this.animate);
},
initControls() {
orbitControls = new OrbitControls(
camera,
renderer.domElement
);
// 惯性
orbitControls.enableDamping = true;
// 动态阻尼系数
orbitControls.dampingFactor = 0.1;
// 缩放
orbitControls.enableZoom = true;
// 右键拖拽
orbitControls.enablePan = true;
orbitControls.minDistance = 10;
orbitControls.maxDistance = 300;
// // 水平旋转范围
orbitControls.maxAzimuthAngle = Math.PI / 2;
orbitControls.minAzimuthAngle = -Math.PI / 2;
// // 垂直旋转范围
orbitControls.maxPolarAngle = Math.PI / 2;
orbitControls.minPolarAngle = -Math.PI / 2;
},
loadModel(){
let loader = new GLTFLoader();
let self = this;
return new Promise(function(resolve, reject){
loader.load(self.resource.modelurl,
gltf => {
var m = gltf.scene;
m.scale.set(3,3,3);
scene.add(m);
},
xhr => {
// 模型加载期间的回调函数
},
error => {
// 模型加载出错的回调函数
console.log("error while loading", error);
reject("load model error", error);
}
)
})
}
}
}
</script>
<style scoped>
.model{
position: relative;
}
#modelbox{
background: #fff;
width: 16rem;
height: 10rem;
}
.close{
position: absolute;
right: 2rem;
top: 2rem;
width: 1rem;
}
</style>