问题
I'm having some issues figuring out how to get GLTFLoader to work in THREE.js. I don't understand how to use a cdn site to host the file. I have tried using links from examples around the web but that hasn't done the job for me. I read on another post that the GLTFLoader file had to be the same versions the core THREE file I'm using (r121).
I thought I could go to mrdoob github (not familiar with how to use github) and click raw file then use that link on a site like githack to generate a cdn link and add it as a script in my html, or import it into my js file, but that didn't work.
If that is the way to do it then it's not working. In my code when I type in:
let loader = new GLTFLoader(); //from the docs
//or
let loader = new THREE.GLTFLoader(); //not from the docs
I get one or the other of these two errors: Uncaught ReferenceError: GLTFLoader is not defined or Uncaught TypeError: THREE.GLTFLoader is not a constructor
I have been at this for hours and haven't a clue what to do.
CodePen https://codepen.io/jfirestorm44/pen/RwRPJda?editors=0010
The tutorial I'm following if it matters: https://tympanus.net/codrops/2019/10/14/how-to-create-an-interactive-3d-character-with-three-js/
回答1:
Make sure your imports for three.js and GLRFLoader in your html file are placed before your own script. I like to place my own scripts at the very bottom of my html file.
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r121/three.min.js" integrity="sha512-yNJzAsg5JyP91u+sLHlUDULMBd3hmEiVkYeeN1cQBKaLZ7EyT6oH2u5THNIRM2Fu6VKcZJv+F/QAp1h/qzy9Ow==" crossorigin="anonymous"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/GLTFLoader.js"></script>
In your script you won't need additional imports, just call the loader
const gltfLoader = new THREE.GLTFLoader();
In other words, the following code is redundant given you use the html imports provided above.
import * as THREE from "https://cdn.jsdelivr.net/npm/three@0.121.1/build/three.module.js";
import { GLTFLoader } from "https://cdn.jsdelivr.net/npm/three@0.121.1/examples/jsm/loaders/GLTFLoader.js";
Working example:
index.html
<!DOCTYPE html>
<html>
<head>
<!-- css imports-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r121/three.min.js" integrity="sha512-yNJzAsg5JyP91u+sLHlUDULMBd3hmEiVkYeeN1cQBKaLZ7EyT6oH2u5THNIRM2Fu6VKcZJv+F/QAp1h/qzy9Ow==" crossorigin="anonymous"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/GLTFLoader.js"></script>
</head>
<body>
<!-- body -->
</body>
<script type="text/javascript" src="/static/myscript.js"></script>
</html>
myscript.js
const gltfLoader = new THREE.GLTFLoader();
来源:https://stackoverflow.com/questions/64409605/how-do-i-load-gltfloader-from-a-cdn-three-js