Home > Net >  Texture won't load - Three.js
Texture won't load - Three.js

Time:10-12

I'm trying to load a texture for my mesh using three.js, but instead of loaded texture I'm getting plain black object. I did it as it is in three.js docs (https://threejs.org/docs/?q=texture#api/en/loaders/TextureLoader - Example) and also tried different solutions but nothing worked. Here is the code

//Creating The Sun model
const sunGeometry = new THREE.SphereGeometry(16, 30, 30);
const texture = new THREE.TextureLoader().load('assets/images/sun.jpg');
const sunMaterial = new THREE.MeshBasicMaterial({ map: texture }); // not working
//const sunMaterial = new THREE.MeshBasicMaterial({ color: 'skyblue' }); //working
const sun = new THREE.Mesh(sunGeometry, sunMaterial);

//Adding The Sun to the Scene
scene.add(sun);

renderer.render(scene, camera);

Setting a mesh color works perfectly fine tho. Also tried using urls, no difference. I'm using Angular and that code is in a constructor
Edit: image path is correct

CodePudding user response:

You're calling renderer.render(scene, camera); immediately after creating your Mesh, but at that time the texture hasn't loaded yet. Textures can take a fraction of a second to load, so by the time they're loaded the rendering has already taken place. If you're calling render() at 60 frames per second, you probably won't notice this delay, but if you're calling it only once, then you'll get a black material.

If you only want to call render() once after the texture has loaded, you should just use the onLoad callback in the method outlined in the code example of the docs page.

  • Related