External models in Three.js
Three.js allows to load external models via JSONLoader()
util. The model itself is a JavaScript file with JSON description of the model, including materials and geometry.
There are two options of getting a JSON model:
You can grab a free 3D model on the internet and convert it to Three.js compatible format with these scripts (notice there are only a few formats supported). Check this video tutorial to get some help. Make sure you have Python installed.
Or make it on your own in Blender or other 3D editor software, and export to JavaScript with one of provided exporters, or save as OBJ and use appropriate converter script.
Now it’s time to load stuff into the browser. Check the source of the demo, it’s just a few llines of code in addition to basic scene setup.
var loader = new THREE.JSONLoader(); // init the loader util
// init loading
loader.load('path_to_model', function (geometry) {
// create a new material
var material = new THREE.MeshLambertMaterial({
map: THREE.ImageUtils.loadTexture('path_to_texture'), // specify and load the texture
colorAmbient: [0.480000026226044, 0.480000026226044, 0.480000026226044],
colorDiffuse: [0.480000026226044, 0.480000026226044, 0.480000026226044],
colorSpecular: [0.8999999761581421, 0.8999999761581421, 0.8999999761581421]
});
// create a mesh with models geometry and material
var mesh = new THREE.Mesh(
geometry,
material
);
mesh.rotation.y = -Math.PI/5;
scene.add(mesh);
});
The callback function of the loader accepts geometry
and materials
, for some reason using of materials from the file won’t load the texture. As a workaround we can create another material with same parameters and load texture in there.