Zurdge
Zurdge

Reputation: 105

ThreeJS - Project texture onto mesh surface

I'm looking to project a texture onto the surface of a mesh in ThreeJS.

https://www.lanyardmarket.com/en/printed-tshirt

This link achieves the result i'm looking for however i'm not sure how they achieved it.

.

I'll update this post as I research however if anyone knows how to project a ThreeJS texture onto a mesh i'd love to know.

Thanks

Upvotes: 4

Views: 3001

Answers (1)

Alex Khoroshylov
Alex Khoroshylov

Reputation: 2354

Working example you may find here: https://jsfiddle.net/mmalex/pcjbysn1/

threejs box texture UV coordinates mapping

BufferGeometry stores texture coordinates in 'uv' attribute, you can add it with BufferGeometry.addAttribute and access it through geom.attributes.uv.array.

let uvcoords = [];
let vertexCount = geom.attributes.position.array.length / 3;

// allocate array of UV coordinates (2 floats per each vertex)
uvcoords.length = 2 * vertCount;

if (geom.attributes.uv === undefined) {
    geom.addAttribute('uv', new THREE.Float32BufferAttribute(uvcoords, 2));
}

Now all you need is to "project" mesh vertices onto some 3D plane. These projection coordinates will appear your UV coordinates.

Projecting mesh vertices on texture UV space (generate uv coordinates)

In general case, you would need to do Plane.projectPoint for each vertex. This approach is straightforward and can be optimized with pre-rotating the mesh so that vertex x and y components become u and v accordingly. This you will find in my jsfiddle.

Upvotes: 5

Related Questions