Unable to render 3D obj file with texture in three.js

I've been trying to display a 3D model with textures on my website using three.js to load .obj and .mtl files. However, for some reason, the model doesn't seem to be appearing. I even tried printing out the obj code itself and it seems fine. Can anyone help me figure out what might be causing this issue? Interestingly, there are no other errors showing up in the console either. The screen shows up with a black background but without the actual model visible. Any assistance would be greatly appreciated. Thank you!

        let container, stats;

        let camera, cameraTarget, scene, renderer;

        init();
        animate();

        function init() {

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

            camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 15 );
            camera.position.set( 0, 0, 0 );

            cameraTarget = new THREE.Vector3( 0, 0, 0 );

            scene = new THREE.Scene();

            var OBJFile = '/program fixture.obj';
            var MTLFile = '/program fixture.mtl';
            const manager = new THREE.LoadingManager();
            manager.addHandler( /\.dds$/i, new DDSLoader() );
            
            new MTLLoader(manager).load(MTLFile, function ( materials ) {
                materials.preload();
                new OBJLoader ( manager ).setMaterials( materials ).load(OBJFile, function ( object ) {
                    console.log(object);
                    scene.add( object );
                });
            });
            

            camera.add( new THREE.PointLight( 0xffffff, 0.8 ) );
            scene.add(camera);

            // renderer

            renderer = new THREE.WebGLRenderer( { antialias: true } );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.outputEncoding = THREE.sRGBEncoding;

            renderer.shadowMap.enabled = true;
            
            container.appendChild( renderer.domElement );
            const controls = new OrbitControls(camera, renderer.domElement)
            controls.enableDamping = true
            controls.target.set(0, 1, 0)

            // stats

            stats = new Stats();
            container.appendChild( stats.dom );

            window.addEventListener( 'resize', onWindowResize );

        }


        function onWindowResize() {

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );

        }

        function animate() {

            requestAnimationFrame( animate );
            render();
            stats.update();

        }

        function render() {

            camera.lookAt( cameraTarget );

            renderer.render( scene, camera );

        }

Answer №1

Your code has a few issues that need to be addressed:

  • Make sure not to call lookAt() in the animation loop if you are already using OrbitControls. Let OrbitControls handle focusing on the target.
  • If damping is enabled, remember to include controls.update() in your animation loop.
  • Avoid placing the camera at the origin as it may cause it to be inside the loaded asset and unable to see it. Also consider increasing the far value of the camera. You can try setting up the camera like this:
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 0, 0, 100 );
  • To ensure your loaded assets are visible, add some lights to your scene. Try incorporating the following:
const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444, 0.6 );
hemiLight.position.set( 0, 20, 0 );
.add( hemiLight );

const dirLight = new THREE.DirectionalLight( 0xffffff, 0.8 );
dirLight.position.set( 0, 100, 100 );
scene.add( dirLight );

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

Ways to access the attribute of the element being hovered over

So, I am currently attaching event listeners to an array of elements with the intention that when a specific element is hovered over, it will set a property to the id of that element. However, instead of grabbing the id of the hovered element, it seems to ...

Retrieve the item within the nested array that is contained within the outer object

I have a collection of objects, each containing nested arrays. My goal is to access the specific object inside one of those arrays. How can I achieve this? For instance, take a look at my function below where I currently log each array to the console. Wha ...

Eliminate items from the array if the property of an object includes any of the provided substrings

In an attempt to minimize the objects within arrays that have a property "Title" containing any substring listed in a separate JSON file, I have been struggling with filtering the arrays based on the object's property. However, I believe using the red ...

Drag and drop to upload files

Is there a way to enable drag-and-drop functionality for uploading and downloading files between a user's computer and web browser? If so, what is the best approach - ASP.NET with AJAX or JS/JQuery? ...

Invoking a function in JavaScript from within the same file

Currently in the process of developing a React application. One of the files I am working with is user.utils.js, where I have stored some utility functions that are utilized within my reducer. export const addUser = (state) => {} export const resetUse ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...

How exactly did Google Fiber design their onboarding guide?

Are you using HTML5 canvas animation or Flash for this website? It's a bit difficult for me to discern. Thank you! ...

The Vue BlogCards Component is missing from the display

My web app is designed to display blog posts in a grid layout. However, the BlogCards component in the Home.vue file is not showing any content as expected. The data is stored in firebase, and when I navigate to /blogs, I can see the blogs displayed in a g ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

In the Swiper function of JavaScript within a Django template, the occurrence of duplicate elements (products) is being generated

Experimenting with displaying products in a Django template, I decided to utilize the Swiper js class. This allowed me to showcase the products within a div, complete with navigation buttons for scrolling horizontally. However, when testing this setup wit ...

The function of modal in JavaScript is not working properly

I am encountering a problem with my web page that is running on Wildfly 12. It is a simple Java EE project that I developed in Eclipse Neon. The issue arises when I try to use Bootstrap modals, as every time I attempt to open or use the methods in a JavaSc ...

Guide to sending back a promise using JQuery

Here is the Durendal code I am working with: var variable = ko.observable(""); function activate(){ return myModel.doSomething(variable); } The doSomething function looks like this: function doSomething(variable){ if(someCondition) return ...

Issue with inconsistent functionality of Socket.io

I've encountered an issue while working with multiple modules - specifically, socket.io is not functioning consistently... We have successfully implemented several 'routes' in Socket.io that work flawlessly every time! However, we are now ...

Guide on how to trigger a pop-up modal to open a new webpage by clicking on a hyperlink

I have a page called one.html that has a link on it <a href="#">Click to open second page<a/> When this link is clicked, I would like for second.html to open in a popup modal. The second page contains a basic table that I want to di ...

XMLHttpRequest is unable to load due to a technical issue

Seeking help to resolve an issue we've encountered. Despite trying various solutions, we keep encountering the Access-Control-Allow-Origin error when attempting to access keen. Error message: Failed to load resource: the server responded with a statu ...

What is the best way to retrieve local variables within a React function?

I keep encountering this issue where I get a TypeError saying that the property 'classList' cannot be read for an undefined value, and this error occurs even before the functions are executed. The specific line causing the error is slide[n].class ...

Ways to display only particular dates in react-dates

I am working with an array of dates. const availableDates = ["2019-02-01", "2019-02-04", "2019-02-05", "2019-02-06", "2019-02-07", "2019-02-11", "2019-02-12", "2019-02-13", "2019-02-14", "2019-02-15", "2019-02-19", "2019-02-20", "2019-02-21", "2019-02-22" ...

Storing a multi-dimensional array in PHP efficiently

My PHP data consists of user limits: $userLimit = array( "default" => array( "playlistLimit" => 1, "mediaLimit" => 2, ), "editor" => array( "playlist ...

Developing a music playlist using javascript/angular (replicating array elements while linking nested objects)

I am currently working on creating a playlist for a music player within an Angular app that includes a shuffle feature. The actual shuffle function is not the issue, as I am utilizing the Fisher Yates Shuffle method and it is functioning correctly. When th ...