Texture may not load on first loading of the page

Hello!
I want to texturize a json object, loaded with object loader:

var objectLoader = new THREE.ObjectLoader();
objectLoader.load("js/teapot-claraio.json", function ( obj ) {
	obj.position.set(0,-1,0);
	scene.add(obj);
	console.log(obj);
	// obj.scale.set(2,2,2);
	
	// var textureLoader = new THREE.TextureLoader();
	// teapotTexture = textureLoader.load('img/textures/crate0/crate0_diffuse.png', 
		// function (material) {
			// obj.material.map = material;
			// console.log('material loaded!');
		// }
	// );
	
	var imgObj =  new Image();
	imgObj.onload = function() {
		var textureLoader = new THREE.TextureLoader();
		teapotTexture = textureLoader.load(imgObj.src, 
			function (material) {
				obj.material.map = material;
				console.log('material loaded!');
			}
		);
	}
	imgObj.src = 'img/textures/crate0/crate0_diffuse.png';
	
} );

but the texture may not load on first loading of the page, even if I use imgObj.onload. Why it is happening?

Hi!
Why not to use THREE.TextureLoader() directly, like in your commented part of the code?

I’m afraid using TextureLoader inside the onload callbcak of Image does not make sense. You would load the image twice. The following approach should work: https://jsfiddle.net/f2Lommf5/13849/

In any event, I can’t recommend this workflow. Instead, use TextureLoader.load() since this method hides unnecessary complexity when loading a texture.

1 Like