user2115136
user2115136

Reputation: 99

trying to understand callback function used in THREEJS

The code below is from a THREE.JS example; works well. I have made my own art gallery reverse engineered from three.js code. The code I am using to hang the paintings originated from the three.js example: webgl_materials_texture_manualmipmap.html

The code below works, but I do not understand how materialPainting1 can be used in the callback function, when it is not fully defined until after the callback function.

Could anyone explain to me how this works please. How the materialpainting1 is used in callback function even though it is defined afterwards, because it works well in the example but in my own code I have to use a fiddle to get the painting to load.

var callbackPainting = function () {
  var image = texturePainting1.image;
  texturePainting2.image = image;
  texturePainting2.needsUpdate = true;
  scene1.add(meshCanvas1);
  scene2.add(meshCanvas2);
  var geometry = new THREE.PlaneGeometry(100, 100);
  var mesh1 = new THREE.Mesh(geometry, materialPainting1);
  var mesh2 = new THREE.Mesh(geometry, materialPainting2);
  addPainting(scene1, mesh1);
  addPainting(scene2, mesh2);

  function addPainting(zscene, zmesh) {
    zmesh.scale.x = image.width / 100;
    zmesh.scale.y = image.height / 100;
    zscene.add(zmesh);
    var meshFrame = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
      color: 0x000000,
      polygonOffset: true,
      polygonOffsetFactor: 1,
      polygonOffsetUnits: 5
    }));
    meshFrame.scale.x = 1.1 * image.width / 100;
    meshFrame.scale.y = 1.1 * image.height / 100;
    zscene.add(meshFrame);
    var meshShadow = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
      color: 0x000000,
      opacity: 0.75,
      transparent: true
    }));
    meshShadow.position.y = -1.1 * image.height / 2;
    meshShadow.position.z = -1.1 * image.height / 2;
    meshShadow.rotation.x = -Math.PI / 2;
    meshShadow.scale.x = 1.1 * image.width / 100;
    meshShadow.scale.y = 1.1 * image.height / 100;
    zscene.add(meshShadow);
    var floorHeight = -1.117 * image.height / 2;
    meshCanvas1.position.y = meshCanvas2.position.y = floorHeight;
  }
};
var texturePainting1 = THREE.ImageUtils.loadTexture("textures/758px-Canestra_di_frutta_(Caravaggio).jpg", THREE.UVMapping, callbackPainting),
  texturePainting2 = new THREE.Texture(),
  materialPainting1 = new THREE.MeshBasicMaterial({
    color: 0xffffff,
    map: texturePainting1
  }),
  materialPainting2 = new THREE.MeshBasicMaterial({
    color: 0xffccaa,
    map: texturePainting2
  });

Upvotes: 1

Views: 1068

Answers (1)

WestLangley
WestLangley

Reputation: 104783

The texture loading is asynchronous; the callback function is not being executed until after the texture loads. By that time, your materials have been defined.

As a matter of good practice, however, I'd define the materials first.

three.js r.66

Upvotes: 2

Related Questions