Using textures in THREE.js

前端 未结 6 1899
遇见更好的自我
遇见更好的自我 2020-11-27 03:16

I am starting with THREE.js, and I am trying to draw a rectangle with a texture on it, lit by a single source of light. I think this is as simple as it gets (HTML omitted fo

6条回答
  •  长情又很酷
    2020-11-27 03:30

    Without Error Handeling

    //Load background texture
     new THREE.TextureLoader();
    loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
                {
                 scene.background = texture;  
                });
    

    With Error Handling

    // Function called when download progresses
    var onProgress = function (xhr) {
      console.log((xhr.loaded / xhr.total * 100) + '% loaded');
    };
    
    // Function called when download errors
    var onError = function (error) {
      console.log('An error happened'+error);
    };
    
    //Function  called when load completes.
    var onLoad = function (texture) {
      var objGeometry = new THREE.BoxGeometry(30, 30, 30);
      var objMaterial = new THREE.MeshPhongMaterial({
        map: texture,
        shading: THREE.FlatShading
      });
    
      var boxMesh = new THREE.Mesh(objGeometry, objMaterial);
      scene.add(boxMesh);
    
      var render = function () {
        requestAnimationFrame(render);
        boxMesh.rotation.x += 0.010;
        boxMesh.rotation.y += 0.010;
          sphereMesh.rotation.y += 0.1;
        renderer.render(scene, camera);
      };
    
      render();
    }
    
    
    //LOAD TEXTURE and on completion apply it on box
    var loader = new THREE.TextureLoader();
        loader.load('https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/The_Earth_seen_from_Apollo_17.jpg/1920px-The_Earth_seen_from_Apollo_17.jpg', 
                    onLoad, 
                    onProgress, 
                    onError);
    

    Result:

    https://codepen.io/hiteshsahu/pen/jpGLpq/

提交回复
热议问题