Trying to dynamically change the texture of a glTF model using the `THREE.TextureLoader`, I successfully changed the color as expected. However, the texture pattern appeared distorted.
Exploring web graphics for the first time, I modified a 3D model viewer example with three.js to load glTF models. My goal was to allow texture changes through buttons, and I opted for glTF due to its perceived standardization. Despite my efforts, including adding `texture.flipY = false;` and tweaking texture object values, I couldn't achieve the desired result.
This snippet shows how I loaded my model:
loader.load( urls, function (texture) {
var pmremGenerator = new THREE.PMREMGenerator( texture );
pmremGenerator.update( renderer );
var pmremCubeUVPacker = new THREE.PMREMCubeUVPacker(pmremGenerator.cubeLods);
pmremCubeUVPacker.update( renderer );
var envMap = pmremCubeUVPacker.CubeUVRenderTarget.texture;
var loader = new THREE.GLTFLoader().setPath( `models/${modelName}/`);
loader.load(`${modelName}.gltf`, (gltf) => {
gltf.scene.traverse((child) => {
if (child.isMesh) {
child.material.envMap = envMap;
}
});
gltf.scene.scale.set(0.01,0.01,0.01)
scene.add(gltf.scene);
});
My attempt to change the texture with a function:
function changeColor(color) {
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load(`models/${modelName}/textures/fabric-${color}.jpg`);
texture.flipY = false;
scene.traverse((child) => {
if (child.isMesh) {
if (child.material.map.format === 1022) {
child.material.map = texture;
}
}
});
}
Although I managed to change the color of the targeted mesh, the texture pattern appeared distorted, specifically on the fabric part of a chair.
In a textual representation:
Intended Pattern:
-------------------
| / / / / / / / / |
| / / / / / / / / |
| / / / / / / / / |
| / / / / / / / / |
| / / / / / / / / |
| / / / / / / / / |
| / / / / / / / / |
-------------------
Figure 1
Actual Pattern:
-------------------
| +++++ |
| +++++ |
| ++++++++++++++ |
| ++++++++++++++ |
| ++++++++++++++ |
| +++++ |
| +++++ |
-------------------
Figure 2
To clarify: How can I maintain the texture pattern like in Figure 1 when changing the texture file using the above function?