1

I'm having some trouble creating a texture from an image file in Three.js. I have a function to create a mesh that looks like this:

    var image = document.createElement('img');
    image.src = imageFile;
    var texture = new THREE.Texture(image);
    var mat = new THREE.MeshPhongMaterial();
    mat.map = texture;

    var mesh = new THREE.Mesh(new THREE.PlaneGeometry(20, 20), mat);
    var plane = mesh;
    plane.position.x = 0;
    scene.add(plane);

However, my texture renders black and the image doesn't seem to render properly.

user3897094
  • 13
  • 1
  • 3

1 Answers1

1

The easiest way to use an image as a texture is to load it using THREE.ImageUtils.loadTexture(url, mapping, onLoad, onError), here is an example:

var mesh = new THREE.Mesh(
    new THREE.PlaneGeometry( 1, 1, 1, 1 ),
    new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('/my-image.jpg') })
);

The THREE.Texture constructor does accept an image as its first parameter, I think the problem you are encountering is because you aren't waiting for the image to complete loading. Using ImageUtils you can avoid having to dealing with callbacks.

hapticdata
  • 1,661
  • 1
  • 12
  • 11