编辑:在 webpack.config.js 中用“url-loader”替换“gltf-webpack-loader”似乎可以解决问题。
我正在尝试使用 Three.js 在 React 应用程序中渲染 3d 模型,但是我是
从本地目录加载 GLTF 文件时出现问题。当我尝试使用 GLTF Loader 加载 GLTF 文件时,出现 404(未找到)错误。它确实有效 当我从外部 URL 加载 GLTF 文件时正确。
GLTF 文件本身可以工作。我在一个单独的非 react 项目(只是一个 html 文件)中测试了它,其中 GLTF 文件使用 GLTFLoader 加载并由本地服务器提供服务。
在单独的非 react 项目中,THREE.js 和 GLTFLoader 加载自
<script src="https://unpkg.com/three@0.102.0/build/three.min.js"></script>
<script src="https://unpkg.com/three@0.102.0/examples/js/loaders/GLTFLoader.js"></script>
而在 React 项目中,它们是从 npm 模块加载的:“three”和“three-gltf-loader”。
下面是我项目中与加载 GLTF 文件相关的代码。
import * as THREE from 'three';
import GLTFLoader from 'three-gltf-loader';
import Car from './models/Low-Poly-Racing-Car.gltf';
...
loader.load(
Car,
(gltf) => {
this.customLayer.scene.add(gltf.scene);
}, null, (err) => {
console.log(err);
}
);
...
同样,这会导致本地文件出现 404 错误,但外部链接如 https://docs.mapbox.com/mapbox-gl-js/assets/34M_17/34M_17.gltf工作得很好。
这是 webpack 版本 1.15.0。我已经尝试过修改和不修改 webpack.config.json。我尝试对 webpack.config.json 的修改是添加
{
test: /\.(gltf)$/,
loader: "gltf-webpack-loader"
},
{
test: /\.(bin)$/,
loader: 'file-loader'
}
加载器数组。这允许
import Car from './models/Low-Poly-Racing-Car.gltf';
工作。
对于 GLTFLoader 的路径参数,我尝试使用上面看到的名为 Car 的变量,以及包含我尝试过的不同目录的相对路径的字符串:
"../../../images/models/Low-Poly-Racing-Car.gltf"
"./models/Low-Poly-Racing-Car.gltf"
"../../../public/models/Low-Poly-Racing-Car.gltf"
"../../../public/models/Low-Poly-Racing-Car.gltf"
当我从上述目录导入名为 Car 的变量时,我得到值:
"/in-memorye5d217e7245bef6f258a6f535019c43e.gltf"
非常感谢任何有关将 GLTF 文件本地加载到此 React 项目的帮助!
最佳答案
If you load models or textures from external files, due to browsers' same origin policy security restrictions, loading from a file system will fail with a security exception.
查看文档:
https://threejs.org/docs/#manual/en/introduction/How-to-run-things-locally
关于webpack - 无法在 React 应用程序中使用 GLTFLoader 从本地目录加载 GLTF 文件。它从外部 URL 正确加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55940928/