Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 613
Andres Avatar asked Jan 21 '16 19:01

Andres


1 Answers

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.

like image 102
2pha Avatar answered Nov 18 '22 09:11

2pha