I’m trying to load a GLB model in the GLTFLoader but I keep getting the error: THREE.GLTFLoader is not a constructor I read already numerous threads here but I can seem to get it solved.
Just some info, I’m trying to load the model via WordPress. I tried a simple geometry shape in Three.js which worked but the GLTFLoader I can’t get working. Any help is much appreciated.
var scene, camera, renderer, hlight;
function init(){
var container = document.getElementById( 'bottle' );
//Create scene
scene = new THREE.Scene();
var fov = 35;
var aspect = container.clientwidth / container.clientHeight;
var near = 0.1
var far = 500;
// Camera Setup
camera = new THREE.PerspectiveCamera(fov,aspect,near,far);
camera.position.set(0, 0, 30);
var ambient = new THREE.AmbientLight(0x404040, 3);
scene.add(ambient);
//Renderer
renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});
renderer.setSize(container.clientWidth, container.clientHeight);
renderer.setPixelRatio(window.devicePixelRatio);
container.appendChild(renderer.domElement);
//Load Model
var loader = new THREE.GLTFLoader();
loader.load('https://creativist-lab.com/wp-content/uploads/2021/04/FibalBrainLogo.gltf', function ( gltf ){
scene.add(gltf.scene);
console.log(gltf);
renderer.render(scene,camera);
});
}
But still without result, the area where the model should be is just blank. These are the errors that I’m seeing:
Uncaught ReferenceError: THREE is not defined
at GLTFLoader.js:3
at GLTFLoader.js:3629
(anonymous) @ GLTFLoader.js:3
(anonymous) @ GLTFLoader.js:3629
So I finally got it working. What ended up being the problem for me is the order of loading the scripts. So in my case the GLTFLoader script loaded before the THREE.js script. When i switched the order around the errors disappeared.
It isn’t safe to import part of the three.js library from one source and a different part from another. Instead try:
import * as THREE from './node_modules/three/build/three.module.js';
import { GLTFLoader } from './node_modules/three/examples/jsm/loaders/GLTFLoader.js';
Also note that the loader must be referenced as GLTFLoader, not THREE.GLTFLoader, when imported in this way.
Ah I see. Still, they must be from the same source. The code published to NPM is meant to be use with a bundler like Parcel, Webpack, or Snowpack, which will automatically handle modules so that you can just import from three or three/examples/jsm/... — if you are not using a bundler, then you will need to import from a single CDN instead. The examples in the three.js CDN installation docs may be helpful.