There seems to be an issue with loading objects using the binary loader in three.js

I have been working on customizing the code of a three.js example to load a .js file that was originally in .obj format. I am using BinaryLoader.js to load the object, however, the object is not appearing in my modified code. Here is what my code looks like so far:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>home</title>
        <meta charset="utf-8>
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        
        <style>
            body {
                background:#000;
                color:#fff;
                padding:0;
                margin:0;
                overflow:hidden;
                font-family:georgia;
                text-align:center;
            }
        </style>

    </head>

    <body>

        <script src="js/three.min.js"></script>
        <script src="loaders/BinaryLoader.js"></script>
        <script src="Detector.js"></script>

        <script>

            if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

            var CARS = {

                "Porsche":  {

                    name:   "Bugatti Veyron",
                    url:    "obj/car/Porsche_911_GT2.js",
                    init_rotation: [ 0, 0, 0 ],
                    scale: 5.5,
                    
                    object: null,
                    buttons: null,
                    materials: null

                }


            };

            var container, stats;

            var camera, scene, renderer;

            init();
            animate();

            function init() {

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

                var loader = new THREE.BinaryLoader( true );
                document.body.appendChild( loader.statusDomElement );

                camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 100000 );
                
                scene = new THREE.Scene();

                var ambient = new THREE.AmbientLight( 0x050505 );
                scene.add( ambient );

                renderer = new THREE.WebGLRenderer();
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( window.innerWidth, window.innerHeight );
                renderer.setFaceCulling( THREE.CullFaceNone );
                renderer.autoClear = false;

                container.appendChild( renderer.domElement );

                loader.load( CARS[ "Porsche" ].url, function( geometry ) { createScene( geometry, "Porsche" ) } );

            }

            function animate() {

            requestAnimationFrame( animate );

            render();

            }

            function render() {

                var timer = -0.0002 * Date.now();

                camera.position.x = 1000 * Math.cos( timer );
                camera.position.y += ( - mouseY - camera.position.y ) * .05;
                camera.position.z = 1000 * Math.sin( timer );

                camera.lookAt( scene.position );
                renderer.render( scene, camera );

            }

        </script>

    </body>
</html>

Does anyone know how to solve this issue?

Answer №1

To display your JSON model correctly, you should use a JSONLoader instead of a BinaryLoader. Additionally, since your model is small, it needs to be scaled by 200 in order to be viewable from your initialized camera with an fov of 70. You can achieve this using the following code:

var loader = new THREE.JSONLoader(true);

loader.load(CARS[ "Porsche" ].url, function (geometry)
{
    /*createScene( geometry, "Porsche" )*/
    var material = new THREE.MeshBasicMaterial({color: 0xff0000});
    var mesh = new THREE.Mesh(geometry, material);
    mesh.scale.set(200,200,200);
    scene.add(mesh);
});

UPDATE: Complete code snippet shown below

<!DOCTYPE html>
<html lang="en">
<head>
    <title>home</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <style>
        body {
            background: #000;
            color: #fff;
            padding: 0;
            margin: 0;
            overflow: hidden;
            font-family: georgia;
            text-align: center;
        }

    </style>
</head>

<body>

<script src="js/three.min.js"></script>

<script src="js/loaders/BinaryLoader.js"></script>

<script src="js/Detector.js"></script>

<script>

    if (!Detector.webgl) {
        Detector.addGetWebGLMessage();
    }
    var mouseY = 0;
    var CARS = {

        "Porsche": {

            name: "Bugatti Veyron",
            url: "obj/car/Porsche_911_GT2.js",
            //  author: '<a href="http://artist-3d.com/free_3d_models/dnm/model_disp.php?uid=1129" target="_blank">Troyano</a>',
            init_rotation: [ 0, 0, 0 ],
            scale: 5.5,
            //init_material: 4,
            //body_materials: [ 2 ],

            object: null,
            buttons: null,
            materials: null

        }


    };

    var container, stats;

    var camera, scene, renderer;

    init();
    animate();

    function init()
    {

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

        var loader = new THREE.JSONLoader(true);
        document.body.appendChild(loader.statusDomElement);
        // CAMERAS

        camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 100000);

        // SCENE

        scene = new THREE.Scene();

        // LIGHTS

        var ambient = new THREE.AmbientLight(0x050505);
        scene.add(ambient);

        renderer = new THREE.WebGLRenderer();
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.setFaceCulling(THREE.CullFaceNone);
        renderer.autoClear = false;

        loader.load(CARS[ "Porsche" ].url, function (geometry)
        {
            /*createScene( geometry, "Porsche" )*/
            var material = new THREE.MeshBasicMaterial({color: 0xff0000});
            var mesh = new THREE.Mesh(geometry, material);
            mesh.scale.set(200,200,200);
            scene.add(mesh);
        });

        container.appendChild(renderer.domElement);

    }

    function animate()
    {

        requestAnimationFrame(animate);

        render();

    }

    function render()
    {

        var timer = -0.0002 * Date.now();

        camera.position.x = 1000 * Math.cos(timer);
        camera.position.y += ( -mouseY - camera.position.y ) * .05;
        camera.position.z = 1000 * Math.sin(timer);

        camera.lookAt(scene.position);
        renderer.render(scene, camera);

    }


</script>
</body>
</html>

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

Depending on external software packages

Can you explain the potential risks associated with using third-party packages and npm in a broader sense? If I were to install a third-party package like semantic-ui-react using npm, is there a possibility that I may not be able to use it on my website i ...

Trying to access a property that doesn't exist (fetching 'fetchBans')

My goal is to create a command within my Discord bot that can unban a user. However, when I finished writing the code, I encountered an error stating 'Cannot read properties of undefined (reading 'fetchBans'). Here is the section of code cau ...

Unable to retrieve the ID from JSON using the QueryParamqq

I need to retrieve two IDs (id and manufacturer_id) from two different tables. Everything works fine, but if I change the parameter value of id=661 in the URL: http://localhost:9999/TestJersey/rest/test/getID?id=661&manufacturer_id=1 An error occurs a ...

How can you pull information from Finnhub.io? (incorporating JSON into a pandas data table)

As a novice in coding, I am eager to learn and explore data from stock markets. My attempt at importing data from finnhub has not been successful so far. import requests import json r = requests.get('https://finnhub.io/api/v1/stock/candle?symbol=QQQ& ...

Having trouble with Mongoose's findOne method not functioning as expected

I am developing an application where users can input data such as the number of hours they slept and their eating habits. This information is then stored in a collection known as the Journal. When a user clicks on "stats", it activates a function called f ...

confirmation message upon completing a form submission

<script> var remainingCredit = document.getElementById("cor_credit"); var remaining = document.getElementById("remain_credit"); function validateForm() { if (remaining.value < remainingCredit.value) { return conf ...

Choosing specific rows in a kogrid by clicking on a button within a column

My kogrid includes a single column with a view button for each row. I would like to show a popup containing the values of the selected row when the View button is clicked. How can I retrieve the values of the selected row in order to pass them into the p ...

Querying for common elements in PostgreSQL JSON arrays

In my database, I have a table with a JSONB data column that is structured like this: data: { "categories": [ "Category A", "Category D" ], "something": "dsa", } My goal is to query rows that contain one or more strings within ...

Having issues with parsing JSON data from the Supreme website using Python

So here is the code I've been working on: import urllib.request, json with urllib.request.urlopen("https://www.supremenewyork.com/mobile_stock.json") as url: data = json.loads(url.read().decode()) print(type(data['Shoes'])) ...

transferring data from Node.js to React

Currently, on my listPage, I have a setup where there are 2 documents. The intention is to allow users to click an edit button which directs them to the editPage. At present, this functionality works as expected. However, the process involves using an axio ...

jq: filter out arrays that include element B and include element A

My information consists of JSON arrays. Each array includes elements with both name and ID keys: [ { "name": "first_source", "id": "abcdef" }, { "name": "second_source", "id": "ghijkl" }, { "name": "third_source", "id": " ...

Bug in Safari/Chrome on IOS: Scroll behavior issue with div using flex-direction:column-reverse

I have a basic div with flex-direction:column-reverse and a button that adds content to the div. When adding values in Chrome, Firefox, Edge on Windows, and in Chrome and Firefox on my Galaxy S21 Ultra, everything behaves as expected. The div stays at scr ...

Swift Data in JSON Format

After receiving the JSON data displayed below, my goal is to extract the "player_name" & "player_country" information. How can I achieve this?**enter image description here If the image fails to load, refer to the output provided: ["team_key": 2 ...

A guide on retrieving a nested JSON file and transferring it into a pandas dataframe

Seeking to enhance my expertise in data science. Currently honing my skills by practicing extracting URL data from a sports site with nested dictionaries in a JSON file. My goal is to create a customized leaderboard using matplotlib, but I'm strugglin ...

What is the solution to having a div move along with window resizing without displacing adjacent divs?

After much effort, I still can't seem to get this working correctly. I've been playing around with a section named "RightExtra" and a div inside it called "RightExtraContent". My goal is to allow these two divs to move freely when the window is ...

What is the process of transforming an xhr request into an angular $http request?

I've been successfully loading images using ajax with the following code. However, when trying to convert it into Angular and use $http, it's not working as expected. Original ajax code var xhr = new XMLHttpRequest(); xhr.open('GET', ...

Creating Positioning Magic with HTML Elements

Currently working on an ASP.NET web app that utilizes a Master, with just a GridView at the bottom and a DIV at the top for further development. The goal is to keep the top DIV or header fixed while scrolling, ensuring it remains in place at the top of th ...

The Json array does not adhere to the correct format

Trying to structure a JSON array in the following format [ "1-35e03ac0b6ba442bb0d5fab3faef32fe", { "request": [ "UpdateComplianceDetail", { "remarks": "Remarks", "next_due_date": "27-Mar-2016", "completion_date" ...

Getting the directory path from JSON using Python

Received an API response in JSON format: "files":[ { "name":"main", "node_type":"directory", "files":[ { "name":"source1", "node_type":"directory", "files":[ { "name ...

Content in RIS JSON API is compressed

I have been exploring the RIS API provided by the German railway. I successfully used the timetable API, which appears to be in JSON format. Link to Timetable API GET https://apis.deutschebahn.com/db-api-marketplace/apis/fahrplan/v1/location/Berlin Header: ...