google / model-viewer

Easily display interactive 3D models on the web and in AR!
https://modelviewer.dev
Apache License 2.0
6.76k stars 801 forks source link

Dynamic color Change #4496

Closed Arumugamsix closed 9 months ago

Arumugamsix commented 9 months ago

We need to change the model color dynamically onload

we have fetched the color name from the query params. at that time we need to change the texture depending on the color from the query params. so we need to change the texture onload. below are the functions written

function switchar() { var queryParams = getUrlQueryParams(); queryParams = queryParams[0] // queryParams = 'https://s3.ap-south-1.amazonaws.com/demo.hnscloud.com/AIS/AIS_config/webar/index.html?webar/assets/Resources/Aluminium/Doors/Casement%20Door/French%20Outwards/models/Alu_Casement_Door_French_Outwards&**Walnut**' var index = queryParams.indexOf('models') if (index !== -1) {
var path = queryParams.substring(0, index) var target = '?' var path1 = queryParams.substring(queryParams.indexOf(target) + target.length); var path2 = path.substring(path.indexOf(target) + target.length); var target1 = '&' var exactPath = path1.substring(0,path1.indexOf(target1)) var colorCode = queryParams.substring(queryParams.indexOf(target1) + target1.length) var finalPath = path2 + 'texture/' + colorCode + '.jpg'; //finalPath = "assets/Resources/Aluminium/Doors/Casement Door/French Outwards/texture/walnut.jpg";

//target = webar/assets/Resources/Upvc/Windows/Sliding Window/3 Panel/models/Upvc_Sliding_Window_3T3P
//target1 = Walnut

} setTimeout(() => { createAndApplyTexture('baseColorTexture',finalPath) }, 2000); //Values = webar/index.html?webar/assets/Resources/Upvc/Windows/Sliding Window/3 Panel/texture/colorcode.jpg document.getElementById('lazy-load').src="https://s3.ap-south-1.amazonaws.com/demo.hnscloud.com/AIS/AIS_config/" + exactPath + ".glb";

// value = target+ texture+ target1.jpg

//https://s3.ap-south-1.amazonaws.com/demo.hnscloud.com/AIS/AIS_config/webar/index.html?webar/assets/Resources/Upvc/Windows/Sliding Window/3 Panel/models/Upvc_Sliding_Window_3T3P&Walnut

// modelViewerTexture.addEventListener("load", (ev) => {

async function createAndApplyTexture  (channel, value)  {
  const modelViewerTexture = document.querySelector("model-viewer#lazy-load");
  let material = modelViewerTexture.model.materials[0];
  try {
    **value = exactPath + 'texture/' + colorCode + '.jpg';**
    let texture = await modelViewerTexture.createTexture(value);
    material.pbrMetallicRoughness[channel].setTexture(texture);
  } catch (error) {
    console.error("Error creating or applying texture:", error);
    // Handle the error appropriately for your app
  }
};

// }) }