Search code examples
three.jstextures

Three.js: texture loaded unproperly


I use some data to create a model in three.js. It can load texture, but with a weird problem. I load the texture in this way.

`function createMesh(geom, imageFile){
     var loader = new THREE.TextureLoader();
     texture = loader.load(imageFile); 
     var mat = new THREE.MeshLambertMaterial({
         side: THREE.DoubleSide, 
     });
    mat.map = texture;
    var mesh = new THREE.Mesh(geom, mat);
    return mesh;}
var geom = new THREE.Geometry();
    geom.vertices = vertices;
    geom.faces = faces;
    geom.computeFaceNormals();
    var myModel = createMesh(geom, './tex1.jpg');
    scene.add(myModel);`  

Here is the screenshot before the texture is loaded.

enter image description here

Here is the screenshot after the texture is loaded.

enter image description here

My texture file(2048*2048.jpg)

enter image description here

I have tested to load the texture in a common cube, and it works. So I can't figure out why the texture can't be loaded in my model. Any suggestions? Thank you very much!


Solution

  • For customized geometry in Three.js, we need to do UV mapping to define how texture is mapped to the geometry.

    Firstly, load the texture by var material = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('texture.jpg') } );

    Then here is how I did UV mapping:

    1. create n arrarys, each corresponding to a sub-image of the texture and contains 4 points which define the boudaries of the sub-image. (0, 0) represents the lower left corner and (1, 1) represents the upper right corner.

    2. clear the existed UV mapping by geometry.faceVertexUvs[0] = [];

    3. Map the sub-image of the texture to each triangle face of the geometry.
      geometry.faceVertexUvs[0][0] = [ sub_image_1[0], sub_image_1[1], sub_image_1[3] ]; geometry.faceVertexUvs[0][1] = [ sub_image_1[1], sub_image_1[2], sub_image_1[3] ];

    Finally, mesh = new THREE.Mesh(geometry, material);