react three.js 解决DRACOLoader 无法设置setDecoderPath 问题

在React18项目中,使用three.js加载被压缩的.glb模型文件时,由于缺少DRACOLoader导致错误。解决方法是引入DRACOLoader,设置解码器路径和类型,预加载解码器,并在GLTFLoader中配置DRACOLoader,从而成功解压并加载模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如图: react18 + three.js 渲染被压缩的.glb文件时报错

 // 创建gltfloader
  const gltfLoader = new GLTFLoader();

  gltfLoader.loadAsync(require('./model/city.glb')).then((gltf) => {
      console.log(gltf);
      scene.add(gltf.scene);
  });

控制台报错:

Uncaught (in promise) Error: THREE.GLTFLoader: No DRACOLoader instance provided.

在这里插入图片描述
解决办法:
设置dracoLoader路径
https://www.gstatic.com/draco/versioned/decoders/[version]/
https://www.gstatic.com/draco/versioned/decoders/1.5.6/
版本号来自 ★ 非常重要 https://github.com/google/draco/tree/master

完整代码

import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
...
// 加载被压缩的.glb文件会报错,需要draco解码器
const dracoLoader = new DRACOLoader();
// 设置dracoLoader路径
dracoLoader.setDecoderPath(
      'https://www.gstatic.com/draco/versioned/decoders/1.5.6/'
);
// 使用js方式解压
dracoLoader.setDecoderConfig({ type: 'js' }); 
// 初始化_initDecoder 解码器
dracoLoader.preload();
// 设置gltf加载器dracoLoader解码器
gltfLoader.setDRACOLoader(dracoLoader);
gltfLoader.loadAsync(require('./model/city.glb')).then((gltf) => {
    console.log(gltf);
    scene.add(gltf.scene);
});

结束~
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值