I am diving into the world of JavaScript and exploring Three.JS, a fascinating new frontier for me. Recently, I managed to convert an obj file into a JSON object and successfully loaded it onto my website using THREE.JSONLoader in three.js. The object displays flawlessly as intended, but now I find myself wanting to interact with it further - rotate, animate, manipulate like any other THREE.Mesh Object would allow. My initial attempt was to mimic the rotation and animation of a cube demonstrated in the very first three.js tutorial, specifically focusing on a mesh chair. However, when I tried to implement the rotation within the "animate()" function after loading the object, I encountered an error claiming that my variable, "myChair", is undefined:
myChair.rotation.x += 0.1;
I suspect there might be an additional step required for three.js to recognize this JSON data as a genuine THREE.Mesh object?
Below is the code snippet:
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();
Thank you for any guidance or assistance offered! Your help means a lot.
UPDATE: following Marco's advice.
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();