In my quest to apply a texture file to a 3D model using three.js, I've hit a roadblock. Despite days of research and numerous attempts, I just can't seem to get it right. Here is the method I've been using to set the current object in the scene:
/**
* SET method: Sets object in the scene (deleting previous one)
*
* @author Anton Pernisch <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16777862797856667364787f65757e38727360">[email protected]</a>>
* @param {string} modelPath - Path to object in glTF format
* @param {string} texturePath - Path to texture
* @returns {boolean}
*
* @todo Texture
*/
SET_Object: function(modelPath, texturePath) {
// Clear out the scene
for (var i = this.prodconf3_scene.children.length - 1; i >= 0; i--) {
obj = this.prodconf3_scene.children[i];
this.prodconf3_scene.remove(obj);
}
const modelLoader = new THREE.GLTFLoader();
modelLoader.load(modelPath, (gltf) => {
// HERE? apply texture from texturePath to this gltf
this.prodconf3_obj = gltf.scene;
this.prodconf3_scene.add(this.prodconf3_obj);
});
return true;
}
The importation of the glTF works fine but the model appears black on the screen. After much trial and error, I managed to somewhat apply a .jpeg texture to the model resulting in this outcome: here.
My approach involved the following method:
/**
* SET method: Sets current object to scene (deleting previous one)
*
* @author Anton Pernisch <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bfaf5eff4f5dbebfee9f5f2e8f8f3b5fffed">[email protected]</a>>
* @param {string} modelPath - Path to object in glTF format
* @param {string} texturePath - Path to texture
* @returns {boolean}
*
* @todo Texture
*/
SET_Object: function(modelPath, texturePath) {
// Clear out the scene
for (var i = this.prodconf3_scene.children.length - 1; i >=0 ; i--) {
obj = this.prodconf3_scene.children[i];
this.prodconf3_scene.remove(obj);
}
const modelLoader = new THREE.GLTFLoader();
const textureLoader = new THREE.TextureLoader();
modelLoader.load(modelPath, (gltf) => {
var model = gltf.scene;
model.traverse((o) => {
if (o.isMesh) {
o.material = new THREE.MeshBasicMaterial({map: textureLoader.load(texturePath)});
}
});
this.prodconf3_obj = model;
this.prodconf3_scene.add(this.prodconf3_obj);
});
return true;
}
I also attempted to create a texture using the TextureLoader load method and then combine it with `gltf.scene` from the `modelLoader.load` function. However, this resulted in an error message:
Uncaught TypeError: Cannot read property 'center' of undefined
I'm unsure about using `gltf.scene` as the first argument in `THREE.Mesh()`.
Can anyone provide guidance on the correct and updated way to apply textures to glTF models in three.js?