Ryan - Llaver Ryan - Llaver - 5 months ago 28
JSON Question

Loading a JSON model in three.js

I have been trying to display a 3D json model using three.js. I am fairly new to three.js and have tried everything I can think of, but don't know anything else to try.

Currently when I try to load the model I get an error that says:

Uncaught TypeError: Cannot read property 'visible' of undefinedr @ three.min.js:602r @ three.min.js:602render @ three.min.js:649render @ test.html:106animate @ test.html:100


I really am not sure where to go from here. Thanks for any help.

Here is my code:

<script type="text/javascript">
if (!Detector.webgl) Detector.addGetWebGLMessage();

var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = 0;

var container;

var camera, scene;
var webglRenderer;

var zmesh, geometry;

var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

document.addEventListener(
'mousemove',
onDocumentMouseMove,
false
);
init();

animate();

// Renderer
webglRenderer = new THREE.WebGLRenderer();
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = 'relative';
container.appendChild(webglRenderer.domElement);

// Loader
var loader = new THREE.JSONLoader(),
callbackModel = function(geometry) {
createScene(geometry, 90, FLOOR, -50, 105)
};
loader.load('can.js', callbackModel);




function init() {
container = document.createElement('div');
document.body.appendChild(container);

// Camera
camera = new THREE.PerspectiveCamera(
75,
SCREEN_WIDTH / SCREEN_HEIGHT,
1,
100000
);
camera.position.z = 75;

// Scene
scene = new THREE.Scene();

// Lights
var ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);

// More lights
var directionalLight = new THREE.DirectionalLight(0xffeedd);
directionalLight.position.set(0, -70, 100).normalize();
scene.add(directionalLight);
}



function createScene( geometry, x, y, z, b ) {
zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );
zmesh.position.set( 0, 16, 0 );
zmesh.scale.set( 1, 1, 1 );
scene.add( zmesh );
}

function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX);
mouseY = (event.clientY - windowHalfY);
}

function animate() {
requestAnimationFrame(animate);
render();
}

function render() {
if(webglRenderer != undefined && zmesh != undefined) {
zmesh.rotation.set(-mouseY/500 + 1, -mouseX/200, 0);
webglRenderer.render(scene, camera);
}
}
</script>

Answer

If your JSON file contains material information, then a materials array will passed to your callback function, and you need to do this:

callbackModel = function( geometry, materials ) {
    // your code
};
...
zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );

Otherwise, you need to define your own material. For example,

zmesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: 0xff000 } ) );

three.js r.77

Comments