简体   繁体   中英

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

I imported from cdn ObjLoader2(). I'm trying to load an obj file but on the console I get two errors:

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.

and...

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

Here's my code:

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

I think it's a problem with library importing, but I don't understand the error. How do I resolve this?

looks like you're running things locally, and due to browsers' same origin policy security restrictions, loading from a file system will fail with a security exception.

You need to run your code on a local web server in order to load 3D models.

You can follow how to on three.js's official website and documentation.

How to run things locally

Loading 3D Models

Hope this helps! Best of Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM