Skip to content Skip to sidebar Skip to footer

Mapping Of Image On Sphere Using Three.js

I'm trying to UV map a cube-map texture onto a sphere. I have tried to Map a cube-map onto a cube and it was pretty easy. I had this image which was mapped onto the cube as follows

Solution 1:

A SphereGeometry does not have vertices in the correct locations to achieve the mapping you want. However, you can easily create a suitable geometry by morphing BoxGeometry into a sphere.

// geometry
var geometry = new THREE.BoxGeometry( 10, 10, 10, 8, 8, 8 );

// morph box into a sphere
for ( var i = 0; i < geometry.vertices.length; i ++ ) {

    geometry.vertices[ i ].normalize().multiplyScalar( 10 ); // or whatever size you want

}

// texture is a collage; set offset/repeat per material index
var repeat = new THREE.Vector2( 1/3, 1/2 );
var offsets = [ 
    new THREE.Vector2( 0, 0 ),
    new THREE.Vector2( 0, 1/2 ),
    new THREE.Vector2( 1/3, 0 ),
    new THREE.Vector2( 1/3, 1/2 ),
    new THREE.Vector2( 2/3, 0 ),
    new THREE.Vector2( 2/3, 1/2 )
];

// redefine vertex normals consistent with a sphere; reset UVs
for ( var i = 0; i < geometry.faces.length; i ++ ) {

    var face = geometry.faces[ i ];

    face.vertexNormals[ 0 ].copy( geometry.vertices[ face.a ] ).normalize();
    face.vertexNormals[ 1 ].copy( geometry.vertices[ face.b ] ).normalize();
    face.vertexNormals[ 2 ].copy( geometry.vertices[ face.c ] ).normalize();

    var uvs = geometry.faceVertexUvs[ 0 ];

    for ( var j = 0; j < 3; j ++ ) {

        uvs[ i ][ j ].multiply( repeat ).add( offsets[ face.materialIndex ] );

    }

    // face.normal - will not be used; don't worry about it

}

var loader = new THREE.TextureLoader();
var texture = loader.load( 'texture.jpg' );

// mesh
var mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { map: texture } ) );
scene.add( mesh );

three.js r.77


Post a Comment for "Mapping Of Image On Sphere Using Three.js"