Texturing a Cylinder in Three.js
[edit] Three cylinders didn't work since the cap UVs are bogus. You need to roll your own cap geometries. Not a lot of work, just annoying. Here's how to do an uncapped cylinder with custom caps:
var coin_sides_geo =
new THREE.CylinderGeometry( 10.0, 10.0, 1.0, 100.0, 10.0, true );
var coin_cap_geo = new THREE.Geometry();
var r = 10.0;
for (var i=0; i<100; i++) {
var a = i * 1/100 * Math.PI * 2;
var z = Math.sin(a);
var x = Math.cos(a);
var a1 = (i+1) * 1/100 * Math.PI * 2;
var z1 = Math.sin(a1);
var x1 = Math.cos(a1);
coin_cap_geo.vertices.push(
new THREE.Vertex(new THREE.Vector3(0, 0, 0)),
new THREE.Vertex(new THREE.Vector3(x*r, 0, z*r)),
new THREE.Vertex(new THREE.Vector3(x1*r, 0, z1*r))
);
coin_cap_geo.faceVertexUvs[0].push([
new THREE.UV(0.5, 0.5),
new THREE.UV(x/2+0.5, z/2+0.5),
new THREE.UV(x1/2+0.5, z1/2+0.5)
]);
coin_cap_geo.faces.push(new THREE.Face3(i*3, i*3+1, i*3+2));
}
coin_cap_geo.computeCentroids();
coin_cap_geo.computeFaceNormals();
var coin_sides_texture =
THREE.ImageUtils.loadTexture("./coin_sides.png");
var coin_cap_texture =
THREE.ImageUtils.loadTexture("./coin_face.png");
var coin_sides_mat =
new THREE.MeshLambertMaterial({map:coin_sides_texture});
var coin_sides =
new THREE.Mesh( coin_sides_geo, coin_sides_mat );
var coin_cap_mat = new THREE.MeshLambertMaterial({map:coin_cap_texture});
var coin_cap_top = new THREE.Mesh( coin_cap_geo, coin_cap_mat );
var coin_cap_bottom = new THREE.Mesh( coin_cap_geo, coin_cap_mat );
coin_cap_top.position.y = 0.5;
coin_cap_bottom.position.y = -0.5;
coin_cap_top.rotation.x = Math.PI;
var coin = new THREE.Object3D();
coin.add(coin_sides);
coin.add(coin_cap_top);
coin.add(coin_cap_bottom);
In modern Three.js you can create a cylinder with an array of 3 materials:
const materials = [
sideMaterial,
topMaterial,
bottomMaterial
]
const geometry = new THREE.CylinderGeometry(5, 5, 0.5, 100)
const mesh= new THREE.Mesh(geometry, materials)