three中使用GLTF/GLB模型性能优化

2,801 阅读1分钟

背景:前端页面应用three展示大量模型,要求优化页面运行稳定性,如果模型总量太大,会导致页面掉帧,严重会导致页面崩溃。

结果:大幅度压缩模型大小,最高压缩掉原来大小的95%

1. 需要插件 three、gltf-pipeline

项目内应用时 npm i three   或者 yarn add three
npm i -g gltf-pipeline  或者 yarn global add gltf-pipeline

2. gltf/glb、压缩

    a、glb转为gltf

        gltf-pipeline -i demol.glb -o demol.gltf
    
    b、gltf压缩

        gltf-pipeline -i demol.gltf -o modelDraco.gltf -d

3.项目中使用

   a、从three的npm包中查找到draco文件,并放置到public文件夹下
        路径为 node_module/three/examples/js/libs/draco
    
   b、引入dracoLoader  GLTFloader

        import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader"

        import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
   c、加载

        const loader = new GLTFLoader();
        let dracoLoader = new DRACOLoader();
        dracoLoader.setDecoderPath("./draco/gltf/"); // 设置public下的解码路径,注意最后面的/
        dracoLoader.setDecoderConfig({ type: "js" });
        dracoLoader.preload();
        loader.setDRACOLoader(dracoLoader);
        loader.load("./glb/trunk_endcar_d.gltf", (gltf) => {
          let model = gltf.scene;
        });

4.OK