Here's my Three.js code that loads a mesh from the file /models/mountain.json using a JSON loader:
var Three = new function () {
this.scene = new THREE.Scene()
// Camera setup
this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000)
this.camera.position.set(20, 52, 20);
// Camera rotation
this.camera.rotation.order = 'YXZ';
this.camera.rotation.y = -Math.PI / 4;
this.camera.rotation.x = Math.atan(-1 / Math.sqrt(2));
this.camera.scale.addScalar(1);
// Renderer setup
this.renderer = new THREE.WebGLRenderer()
this.renderer.setSize(window.innerWidth, window.innerHeight);
var ground = new THREE.Mesh(
new THREE.PlaneBufferGeometry(436, 624),
new THREE.MeshLambertMaterial({color: '#808080'}));
ground.rotation.x = -Math.PI / 2; //-90 degrees around the x axis
this.scene.add(ground);
// Point light
var light = new THREE.PointLight(0xFFFFDD);
light.position.set(-1000, 1000, 1000);
this.scene.add(light);
var loader = new THREE.JSONLoader();
// Load mountain function
this.loadMountain = function (x, y) {
loader.load('/models/mountain.json', Three.getGeomHandler('#808080', x, y, 1))
}
// Load multiple mountains
this.loadFields = function () {
for (var i=0;i<4000;i++) {
Three.loadMountain(x, y)
}
}
// Geometry handler
this.getGeomHandler = function (color, x, y, scale) {
return function (geometry) {
var mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({color: color}));
mesh.scale.set(scale, scale, scale);
mesh.position.set(x, 0, y);
Three.scene.add(mesh);
};
}
// Initialize Three.js
this.init = function () {
$('body').append(Three.renderer.domElement);
Three.loadFields()
Three.render();
}
// Render function
this.render = function () {
requestAnimationFrame(Three.render);
Three.renderer.render(Three.scene, Three.camera);
};
}
$(document).ready(function () {
Three.init();
});
This is the content of /models/mountain.json:
{
"metadata": {
"formatVersion" : 3.1,
"generatedBy" : "Blender 2.7 Exporter",
...
}
}
Would it be possible to use the content of mountain.json as a variable in our code and add it to the scene?