Back to the Shapespark home page

Replace any material

Hi
I’m trying to customize this.
https://github.com/shapespark/shapespark-viewer-api#replace-textures-using-images-or-videos-from-external-source

Refer to this
After obtaining the clicked material name,
I want to replace the texture by clicking the texture on the screen.

But my script doesn’t work.

<script>
  var viewer = WALK.getViewer();
	viewer.onMaterialClicked(function(material){
    var materialName = [];
		viewer.setMaterialEditable(materialName);
		return true;
	});
  var textureElementIds = ['brick', 'brick2', 'metal', 'stone', 'tiles',
                           'yellow', 'dots-video', 'lines-video',
                           'squares-video'];
  textureElementIds.forEach(function(textureElementId) {
    var textureElement = document.getElementById(textureElementId);
    var texture = null;
    textureElement.addEventListener('click', function() {
      if (texture === null) {
        if (textureElement instanceof HTMLVideoElement) {
          texture = viewer.createTextureFromHtmlVideo(textureElement);
        } else {
          texture = viewer.createTextureFromHtmlImage(textureElement);
        }
      }
      var material = viewer.findMaterial(materialName);
			viewer.setMaterialForMesh(material, mesh){
			material.baseColorTexture = texture;}
      viewer.requestFrame();
    });
  });
</script>

Please,let me know.

Try this:

  var viewer = WALK.getViewer();
  viewer.setAllMaterialsEditable();
  var textureElementIds = ['brick', 'brick2', 'metal', 'stone', 'tiles',
                           'yellow', 'dots-video', 'lines-video',
                           'squares-video'];
  var clickedMaterial;
  textureElementIds.forEach(function(textureElementId) {
    var textureElement = document.getElementById(textureElementId);
    textureElement.addEventListener('click', function() {
      if (!clickedMaterial) {
        return;
      }
      var texture;
      if (textureElement instanceof HTMLVideoElement) {
        texture = viewer.createTextureFromHtmlVideo(textureElement);
      } else {
        texture = viewer.createTextureFromHtmlImage(textureElement);
      }
      clickedMaterial.baseColorTexture = texture;
      viewer.requestFrame();
    });
  });
  viewer.onNodeTypeClicked(function(node){
    clickedMaterial = node.mesh.material;
    return true;
  });

Thanks!
this worked perfectly.