本文提供了在three.js中实现:将glb或gltf格式的模型加载并显示在页面中 的方法

以下将提供两种情况下的加载步骤:

一、原生JS中,加载模型:

注意,欲通过import导入文件,需设置<script type="module">

import {} from "./three/build/three.js";
import { GLTFLoader } from "./three/examples/jsm/loaders/GLTFLoader.js";

        const loader = new GLTFLoader();
            // 加载地图模型
            loader.load('./map.glb', function(gltf){
                //将模型添加至场景
                scene.add(gltf.scene)
                //设置模型位置
                gltf.scene.position.set(0,-100,0)
            })

这部分仅提供加载模型的方法,在方法体内可以添加相关代码,对模型进行旋转、缩小、放大,以及各种对模型的其他操作。

二、vue+three.js,加载模型,并且通过DRACOLoader压缩模型

import * as Three from "three"; //引入Threejs
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
loadGltf() {
            const loader = new GLTFLoader()
            const dracoLoader = new DRACOLoader()
            dracoLoader.setDecoderPath('/draco/')
            dracoLoader.preload()
            loader.setDRACOLoader(dracoLoader)
            loader.load('static/model/map.glb', (gltf) => {
                gltf.scene.position.set(0,0,0)
                let axis = new Three.Vector3(0,1,0);//向量axis
                gltf.scene.rotateOnAxis(axis,Math.PI/2);
                //绕axis轴逆旋转π/16
                gltf.scene.rotateOnAxis(axis,Math.PI/-20);
                gltf.scene.rotateOnAxis(axis,Math.PI/50);
                //gltf.rotateY(Math.PI / 2);
                this.scene.add(gltf.scene)
                this.renderer.render(this.scene, this.camera)
            }, (xhr) => {
                console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
            }, (error) => {
                console.error(error)
            })
    },

在three.js中,glb格式的模型与gltf格式的模型加载方式相同,均通过GLTFLoader加载器进行加载。

当然,当建模部分不支持GLTF或GLB格式模型的导出时,也会涉及到其他模型的加载。three.js中也提供了多个其他格式模型的加载器,例如OBJLoader,MTLLoader等。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐