Sebastian Johansson
Sebastian Johansson

Reputation: 27

Three.js Mesh loads correctly but not showing

Im trying to apply Texture to my sphere using Three.js. I'm running a Python server.

Console prints Success! image-size: 1024 x 1024. Can't figure out what the problem is.

Main.js:

const scene = new THREE.Scene()
const geometry = new THREE.BoxGeometry(1, 1, 1)
const texture = texLoader.load('Fabric_Lace_026_height.png', 

// On success
function(texture) {
    console.log("Success!");
    console.log(texture);
},

// Progress (ignored)
undefined,

// On error
function(err) {
    console.log("Error");
    console.log(err);}
);

const material = new THREE.MeshBasicMaterial({map: texture})
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)

const sizes = {width: window.innerWidth,height: window.innerHeight}


const camera = new THREE.PerspectiveCamera(75, sizes.width /sizes.height, 1, 1000)
camera.position.z = 3

const canvas = document.querySelector('canvas.webgl')

const renderer = new THREE.WebGLRenderer({canvas: canvas})
renderer.setSize(sizes.width, sizes.height)
renderer.render(scene, camera)

Upvotes: 2

Views: 588

Answers (1)

Mugen87
Mugen87

Reputation: 31076

You are rendering your scene too early. Since you have no animation loop, you have to call render() when the texture is fully loaded. Try it like so:

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 3;

//

const loader = new THREE.TextureLoader();
const texture = loader.load('https://threejs.org/examples/textures/uv_grid_opengl.jpg',

  // On success
  function(texture) {
    renderer.render(scene, camera); // FIX
  },

  // Progress (ignored)
  undefined,

  // On error
  function(err) {
    console.log(err);
  }
);

//

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({map: texture});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

//

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
body {
      margin: 0;
}
<script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>

Upvotes: 1

Related Questions