无法使用 three.js 和 ObjLoader2 加载 obj 文件

Can't load an obj file with three.js and ObjLoader2

我是从cdn ObjLoader2()导入的。我正在尝试加载一个 obj 文件,但在控制台上出现两个错误:

Access to XMLHttpRequest at 'myfilepath.obj' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

和...

three.module.js:35911 GET myfilepath.obj net::ERR_FAILED
load    @   three.module.js:35911
load    @   OBJLoader2.js:301
(anonymous) @   index.html:31

这是我的代码:

  <script src="js/three.js"></script>
  <script src="js/three.min.js"></script>
  <script type="module">
      import { OBJLoader2 } from "https://threejsfundamentals.org/threejs/resources/threejs/r115/examples/jsm/loaders/OBJLoader2.js";
      import { OrbitControls } from "https://threejsfundamentals.org/threejs/resources/threejs/r122/examples/jsm/controls/OrbitControls.js";
      const canvas = document.querySelector("#canvasObj");
      const renderer = new THREE.WebGLRenderer({ canvas });
      const fov = 45;
      const aspect = 2;
      const near = 0.1;
      const far = 5;
      const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
      camera.position.set(0, 5, 2);
      const scena = new THREE.Scene();
      const objLoader = new OBJLoader2();
      objLoader.load("Iphone8.obj", (root) => {
        scena.add(root);
        render();
      });
        renderer.render(scena, camera);
    </script>

我认为是库导入的问题,但我不明白错误。我该如何解决?

看起来您是在本地 运行 处理事情,并且由于浏览器的同源策略安全限制,从文件系统加载将失败并出现安全异常。

您需要 运行 您的代码在本地网络服务器上才能加载 3D 模型。

您可以在 three.js 的官方网站和文档中查看操作方法。

How to run things locally

Loading 3D Models

希望对您有所帮助!祝你好运!