Three.js支持将场景导出成gltf(glb)格式三维模型,以文件的形式进行存储,下面以代码的形式说明,如何将场景导出模型。
初始化场景
初始化一个Three.js场景,这个场景不需要显示,也能够将模型进行导出,简单代码如下:
initthreescene() {
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0xcfcfcf);
this.rendererScene();
},
rendererScene() {
this.renderer = new THREE.WebGLRenderer({
antialias: true,
});
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setSize(300, 500);
}
场景导出模型
需要单独引用Three.js example的文件:
import { GLTFExporter }
from "three/examples/jsm/exporters/GLTFExporter.js";
初始化Exporter,初始化一遍即可:
this.igltfexporter = new GLTFExporter();
导出gltf模型配置:
const options = {
//true导出位置、缩放、旋转变换,false导出节点的矩阵变换
trs: false,
//是否只导出可见的
onlyVisible: true,
truncateDrawRange: true,
//是否二进制,true导出glb模型,false导出gltf模型
binary: false,
//最大贴图尺寸
maxTextureSize: Infinity,
};
this.igltfexporter.parse(
this.scene,
function (result) {
//result即是gltf文件,写入到本地
},
options
);
导出glb模型配置:
const options: {
trs: false,
onlyVisible: true,
truncateDrawRange: true,
binary: true,
maxTextureSize: Infinity,
},
scope.igltfexporter.parse(
this.scene,
function (result) {
if (result instanceof ArrayBuffer) {
//result即为glb模型
}
},
options
);
参考引用:
https://threejs.org/examples/?q=gltf#misc_exporter_gltf