1,安装three 和 three-orbitcontrols
npm i -s three
npm i three-orbitcontrols
2,在public下面创建static放置模型文件
文件目录
3,在页面引入three
import * as THREE from "three";
import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader";
4,初始化
init() {
let container = document.getElementById("container");
this.scene = new THREE.Scene();
this.scene.add(new THREE.AmbientLight(0x404040, 6));
this.light = new THREE.DirectionalLight(0xdfebff, 0.45);
this.light.position.set(50, 200, 100);
this.light.position.multiplyScalar(0.3);
this.scene.add(this.light);
this.camera = new THREE.PerspectiveCamera(
70,
container.clientWidth / container.clientHeight,
0.01,
10
);
this.camera.position.z = 1;
this.renderer = new THREE.WebGLRenderer({alpha: true});
this.renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(this.renderer.domElement);
},
5,加载模型以及动画
loadGltf() {
let self = this;
let loader = new GLTFLoader();
loader.load("static/mod/Xbot.glb", function (gltf) {
self.isLoading = false;
self.mesh = gltf.scene;
self.mesh.scale.set(0.3, 0.3, 0.3);
self.mesh.position.set(0, 0, 0);
self.scene.add(self.mesh);
self.animate();
});
},
animate() {
if (this.mesh) {
requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
}
},
完整代码
<template>
<div id="import-template">
<div id="container">
</div>
</div>
</template>
<script>
import * as THREE from "three";
import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader";
export default {
name: 'ImportTemplate',
data() {
return {
scene: null,
light: null,
camera: null,
renderer: null,
mesh: null,
group: null
}
},
mounted() {
this.init()
this.loadGltf()
},
methods: {
init() {
let container = document.getElementById("container");
this.scene = new THREE.Scene();
this.scene.add(new THREE.AmbientLight(0x404040, 6));
this.light = new THREE.DirectionalLight(0xdfebff, 0.45);
this.light.position.set(50, 200, 100);
this.light.position.multiplyScalar(0.3);
this.scene.add(this.light);
this.camera = new THREE.PerspectiveCamera(
70,
container.clientWidth / container.clientHeight,
0.01,
10
);
this.camera.position.z = 1;
this.renderer = new THREE.WebGLRenderer({alpha: true});
this.renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(this.renderer.domElement);
},
loadGltf() {
let self = this;
let loader = new GLTFLoader();
loader.load("static/mod/Xbot.glb", function (gltf) {
self.isLoading = false;
self.mesh = gltf.scene;
self.mesh.scale.set(0.3, 0.3, 0.3);
self.mesh.position.set(0, 0, 0);
self.scene.add(self.mesh);
self.animate();
});
},
animate() {
if (this.mesh) {
requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
}
},
}
}
</script>
<style scoped>
#import-template {
width: 1920px;
height: 1080px;
}
#container {
width: 500px;
height: 500px;
margin: 150px auto;
}
</style>