I am attempting to rotate a texture on a single face of a cube using Three.js.
Since I am generating the cube multiple times with different textures, I am utilizing a function that creates the material and mesh with a texture parameter.
However, I need the texture to be rotated by 90°. After some research, I discovered that creating a canvas, placing the texture inside, rotating it, and then using this canvas as the mesh texture would be the best approach. I tried implementing this solution using the code from Three.js Rotate Texture, but unfortunately, I kept getting a black texture.
Below is my function:
function createCube(pos, texture) {
var img = new Image();
img.src = texture;
var imgWidth = imgHeight = img.width;
var mapCanvas = document.createElement('canvas');
mapCanvas.width = mapCanvas.height = img.width;
// document.body.appendChild(mapCanvas);
var ctx = mapCanvas.getContext('2d');
ctx.translate(imgWidth / 2, imgHeight / 2);
ctx.rotate(Math.PI / 2);
ctx.translate(-imgWidth / 2, -imgHeight / 2);
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
var texture = new THREE.Texture(mapCanvas);
texture.needsUpdate = true;
var materials = [
//Left side (posx)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Right side (negx)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Top side (posy)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Bottom side (negy)
new THREE.MeshLambertMaterial({
color: 0xffffff,
map: texture
}),
//Front side (posz)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
}),
//Back side (negz)
new THREE.MeshLambertMaterial({
color: 0x1a0e05
})
];
cube = new THREE.Mesh(new THREE.CubeGeometry(100, 2, 100, 1, 1, 1), new THREE.MeshFaceMaterial(materials));
...
return cube;
}
The issue could potentially be linked to the texture not being fully loaded when added to the canvas.
I removed the img.onLoad
part (from Three.js Rotate Texture) because I was unsure how to integrate this callback within a function called multiple times...
Additionally, this function must return the mesh. Can I achieve this using an external .onLoad
function?
Thank you!