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

问题描述

我从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>

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

解决方法

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

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

您可以在Three.js的官方网站和文档上了解如何操作。

How to run things locally

Loading 3D Models

希望这会有所帮助!祝你好运!

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...