THREE.js Geometry map does not appear

2020-05-01 06:22发布

问题:

Following I'm loading a image map on a custom geometry, it represents the brown colored geometry on the picture above:

var aqua_ground_geo = new THREE.Geometry();

var top0 = new THREE.Vector3(aqua_ground_geo_x_NEG, user_data['aqua_soil_calc_b_y'], aqua_ground_geo_z_NEG);
var top1 = new THREE.Vector3(aqua_ground_geo_x_POS, user_data['aqua_soil_calc_b_y'], aqua_ground_geo_z_NEG);
var top2 = new THREE.Vector3(aqua_ground_geo_x_NEG, user_data['aqua_soil_calc_f_y'], aqua_ground_geo_z_POS);

aqua_ground_geo.vertices.push(top0);
aqua_ground_geo.vertices.push(top1);
aqua_ground_geo.vertices.push(top2);

aqua_ground_geo.faces.push( new THREE.Face3(0,1,2) );

aqua_ground_geo.computeFaceNormals();
aqua_ground_geo.computeVertexNormals();

var textureUrl = "http://www.lifeguider.de/wp-content/uploads/aquag/bodengrund/dennerle_kies_naturweiss_1-2mm.jpg";
var aqua_bodengrund_tex = new THREE.TextureLoader().load( textureUrl );
var aqua_bodengrund_mat = new THREE.MeshLambertMaterial( {
    map: aqua_bodengrund_tex,
    color: 0xffffff,
} );
aqua_bodengrund_mat.shading = THREE.FlatShading;
aqua_bodengrund_mat.side = THREE.DoubleSide;

var aqua_bodengrund = new THREE.Mesh( aqua_ground_geo,aqua_bodengrund_mat);

On a simple THREE.BoxGeometry all works as expected with the same material (it represents the cube in the picture above):

var lala = new THREE.BoxGeometry( 100, 100, 100 );
var lala2 = new THREE.Mesh( lala,aqua_bodengrund_mat);

I'm not an expert in 3D, what is missing in my code that the image texture will be shown correctly?

回答1:

You need to apply the texture in the callback of the THREE.TextureLoader. Check also the documentation here; the second argument (onLoad) is the callback.

var textureUrl = "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/crate.gif";
var aqua_bodengrund_mat = new THREE.MeshLambertMaterial( {
    color: 0xffffff
});
var onLoad = function( texture ){
    aqua_bodengrund_mat.map = texture;
    aqua_bodengrund_mat.needsUpdate = true;
}
var loader = new THREE.TextureLoader();
loader.load( textureUrl, onLoad );

See this fiddle for a demo.


UPDATE

In case you have a custom geometry you also need to calculate the UVs for showing the texture correctly. I used this answer here to calculate them in another fiddle here

Note. The UVs in my fiddle are calculated for faces in the XY plane, if your faces are in another plane you will have to update accordingly...