Importing a JSON model into a three.js environment

I have been attempting to showcase a 3D json model using three.js. Despite being new to three.js, I have exhausted all my options and am unsure of what to do next.

Every time I try to load the model, I encounter an error that reads:

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 am at a loss for what steps to take next. Any assistance would be greatly appreciated.

Below is the code I am working with:

<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 №1

If the JSON file you are working with includes important material information, an array called materials will be passed to your callback function. In this case, you will need to modify your code as follows:

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

If the JSON file does not include material information, you will need to create your own material. For example:

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

This code is written for three.js version r.77

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extracting values from a JSON array

I am attempting to modify values within an array in a JSON object using sed and jq. The structure of the object is as follows: { "alertrulemethoddata": "", "alertruleimportance": 50, "alertruletype": "any& ...

Instructions for generating multiple components in React when an array is not at your disposal

In the process of developing a Tic-Tac-Toe game, I am in need of creating 9 empty squares. Currently, I have a ul element and 9 li elements representing each square in the game. The issue is that there is no array available for looping through and generati ...

The API designed to accept JSON data via a POST request is receiving a different data type than expected

I have a task to develop an API that receives JSON data in NODE.JS via the POST method. To simplify request management, I utilize Express and BodyParser library to handle the body of POST requests. The data is structured in a JavaScript object like this: ...

Is JSON required to transmit an object using socket.io?

I have an object on the frontend that I want to broadcast to all connected clients. Can I send it as is, in its original form? Or do I always have to convert it into a JSON string before sending? Here is my object: var myBox = { x: 400, ...

The redirect link to Facebook Messenger is functional on desktop browsers but experiences difficulties on mobile browsers

Currently, I am facing an issue with redirecting from a webpage to an m.me/?ref= Facebook link that points to a Facebook Page. The redirection works smoothly on the Desktop Browser and opens the Facebook Messenger as expected. However, when attempting the ...

What methods can be utilized to ensure that my wistia video player/playlist is responsive on different devices

I need some assistance with making my Wistia player responsive while using a playlist. I want the video player to adjust its size based on the screen size. Here is an example: My current code utilizes their iframe implementation: <div id="wistia_1n649 ...

Code running successfully in Chrome's console, but encountering issues when executed on the webpage

Having some trouble assigning a function to a button in JavaScript. This is the button I'm working with, and my main goal right now is to make it responsive. <button id="artbtn" class="artbtn btn">Art</button> I experimented with this in ...

Safari and iOS 15 to 14 have rendered the Javascript audio context unusable

Recently, I noticed that the IOS/Safari upgrade has caused some issues with the web audio API. Check out this simple code that used to work on IOS and Safari before the upgrade, but now it doesn't work anymore. Interestingly, it still works on Firefo ...

Why is the Zip archive downloader not functioning properly when using Node.js and Archiver (Unexpected end of archive error)?

Looking to download multiple files using archiver with express. The server should respond to a post request from the client by sending a .zip file. However, there seems to be an issue where WinRAR displays an error message "! 98I9ZOCR.zip:Unexpected end of ...

What is the best way to include the file name and size as query parameters in Node.js?

To retrieve an image from the folder, a query needs to be passed containing the filename and dimensions like this: localhost:3000/images?filename=myImage&width=100&height=100 The initial objective is to fetch images from the designated folder, res ...

Json object not recognized

I am in the process of developing a basic application where the user can interact with a button to retrieve a JSON object from the database. The object's structure is displayed below. However, the system is failing to recognize the object, resulting i ...

Using JQuery validate to extract the interest rate from a regular expression

I am looking for a regular expression that can extract the interest rate. I need it to accept values such as: Examples: 0 0.4 0.44 4 44 4.00 44.00 4.2 4.22 44.22 Minimum value allowed is 0 and maximum is 99.99 The regular expression should be ab ...

What could be causing the issue with ng-include not functioning properly?

Issue with ng-include Organized Directory Structure : ssh_project --public ----templates ------header.html ------footer.html ----views ------index.html Here is the content of my index.html file <body> <h1>Hello</h1> <div ng ...

The statusMessage variable is not defined within the "res" object in a Node Express application

I am currently developing a Node.js & Express.js application and I am in need of creating a route to display the app's status. router.get('/status', function(req, res) { res.send("Current status: " + res.statusCode + " : " + res.stat ...

Simulate a click event on an element generated with JavaScript to initiate the download of a CSV file

I am attempting to generate an HTML element and trigger a click event in order to download a CSV file upon receiving an ajax response (the data array provided is for testing purposes only). $(document).on('click','.csv',function(){ ...

Tips for choosing multiple files with the Ctrl key in a list item element:

We have decided to create our own browsing functionality due to the limitations of the existing HTML browse feature. While using the HTML browse, we can only select multiple files by pressing the Ctrl key, and we want to replicate this feature in our custo ...

Managing the state of dynamically generated tabs within a NextJS application

Looking to develop a web app in Next.js that includes tabs components. The goal is to manage various entities within each tab, such as utilizing a search bar to select different products. Upon selecting a product, a new tab will be generated with the produ ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...

Executing a CRM javascript button triggers a request to a JSON URL and extracts a specific value

My current task involves creating a button in JavaScript due to system limitations preventing the use of HTML. This button should navigate to a specific URL (REST API to retrieve a JSON file). Furthermore, upon clicking the button, I aim to display an aler ...

typescript scrolling location

In my Angular UI code, I have a component class that includes the following structure: app.component.html //... <div class="banner"> <p-dialog [(visible)]="displayCOI" styleClass="coiDialog" [contentStyle]=" ...