Adam Campbell
Adam Campbell

Reputation: 11

How to add images & textures to Three.js JSON object file

My primary goal is to load a 3D model created within 3DS/MAX into WebGL using the awesome Three.js library. I've accomplished the following steps towards that goal.

  1. Attempted to use the MAX plugin exporter straight to Three.js JSON. It was problematic, and did not work.
  2. Exported the MAX model into OBJ format.
  3. Converted the OBJ model into JSON format with the Three.js converter Obj2Three.js.
  4. This works great and I can now load my model into Three.js but it does not have any textures/images applied to it.
  5. Inspected the JSON file and it contains Geometries, Materials, Metadata, and Object sections within it.
  6. The Three.ObjectLoader apparently handles Images and Textures as well, if those section are defined within the file.

So my question is how is this accomplished? Are there any utilities that can help to add textures to the JSON file?

Upvotes: 1

Views: 1979

Answers (1)

Lord Goderick
Lord Goderick

Reputation: 985

You don't need to convert at all. Look into the examples folder of three.js and you should see a whole bunch of loaders. Use the OBJLoader if you want something that is widely used, otherwise I suggest looking at the FBXLoader or ColladaLoader2 since these files are much smaller in size than .obj or JSON. Here is a demo of using the FBXLoader and also adding a texture, but you can use the same concept in every loader:

loadFBX = function(modelPath, texturePath) {

  var container = new THREE.Object3D();

  fbxLoader.load(modelPath, function( object ) {

        container.add(object);

   object.traverse (function (child) {

        if (child instanceof THREE.Mesh) {
           //here's how we add the texture, you may need to
           //UV Unwrap your model first in 3Ds
           child.material = new THREE.MeshLambertMaterial();
           child.material.map = textureLoader.load(texturePath);
        }

     });

    }, onProgress, onError );

    return container;
}

var model = loadFBX('../models/model.fbx', '../textures/texture.png');
scene.add(model);

Why convert when you can load .obj or even .fbx formats directly? But if you really want, there's a very easy method to add textures to your JSON model. Use the online Three.js Editor and drag your .obj or whatever model into the scene. From there you can add the image texture with the visual editor and then export the object as .json. You can then simply load that into the scene and the texture will be included in the JSON file.

Upvotes: 1

Related Questions