How to apply a texture to a custom geometry in Three.js

Andres picture Andres · Jan 21, 2016 · Viewed 14.1k times · Source

I successfully applied a texture to a cube geometry with this:

var geometry = new THREE.CubeGeometry(10, 10, 10);
var meshMaterial = new THREE.MeshPhongMaterial({ transparent: false, map: THREE.ImageUtils.loadTexture('/app/images/wood.jpg') });
meshMaterial.side = THREE.DoubleSide;
var mesh = new THREE.Mesh(geometry, meshMaterial);

With this I get a nice textured cube like this:

enter image description here

Now I want to apply the same texture (512x512 jpg image) to a custom model I'm loading from an STL and this is what I get (in this case a pyramid):

enter image description here

This is the code:

loader.load(jsonParam.url, function (geometry) {
            var meshMaterial = new THREE.MeshPhongMaterial({ transparent: false, map: THREE.ImageUtils.loadTexture('/app/images/wood.jpg') });
            meshMaterial.side = THREE.DoubleSide;

            var mesh = new THREE.Mesh(geometry, meshMaterial);

            mesh.castShadow = false;
            mesh.receiveShadow = true;
            scene.add(mesh);
        });

Why the texture is not being applied and I get only what seems to be an average of the texture colors?

Answer

2pha picture 2pha · Jan 22, 2016

You need UV mapping.
You can either edit the model in modelling software to add UV coordinates or maybe generate them as in the answers posted here.
I suppose another option would be to create your own shader that maps the texture to the model surface without using UV coordinates.