I am new to Javascript and even newer to Three.JS. I have successfully taken a obj and converted and then loaded it in my site as a JSON object via three.js THREE.JSONLoader. It displays fine as I wanted but I need to be able to rotate, animate and manipulate it like any other THREE.Mesh Object. My first attempt at this is to rotate and animate it (a mesh chair) like the cube in the first three.js tutorial. However, after loading the object and attempting to rotate it within the "animate()" function, the variable I have set "myChair" is producing an "undefined" error when written:
myChair.rotation.x += 0.1;
I assume there is another step I must take for three.js to treat this JSON like any THREE.Mesh object?
Here is my code:
viewport = document.getElementById('mycanvas');
h = viewport.offsetHeight;
w = viewport.offsetWidth;
var scene = new THREE.Scene();
scene.background = new THREE.Color( 0xffffff );
var camera = new THREE.PerspectiveCamera( 75, w/h, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize(w, h);
viewport.appendChild(renderer.domElement);
//end viewport
var myChair = new THREE.JSONLoader();
myChair.load(
'https://api.myjson.com/bins/iaxn7',
function ( geometry, materials ) {
var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
var object = new THREE.Mesh( geometry, material );
scene.add(object);
}
);
alert(myChair); //this alert confirms that an object is stored in the variable
var animate = function () {
requestAnimationFrame( animate );
myChair.rotation.x += 0.1;
myChair.rotation.y += 0.1;
renderer.render(scene, camera);
};
animate();
Thanks so much! Any help is much appreciated.
UPDATE: after Marco's response.
var myChairLoader = new THREE.JSONLoader();
var chairMesh = null;
myChairLoader.load(
'https://api.myjson.com/bins/iaxn7',
function ( geometry, materials ) {
var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
var chairMesh = new THREE.Mesh(geometry,material);
scene.add(chairMesh);
renderer.render(scene,camera);
}
);
var animate = function (){
requestAnimationFrame(animate);
if(chairMesh !== null){
alert();
chairMesh.rotation.x += 0.1;
chairMesh.rotation.y += 0.1;
}
renderer.render(scene,camera);
};
animate();