Unable to display Three.JS OBJ Model

I am facing an issue with loading a .obj model in Three.js. I created the model in Cinema 4D, exported it with a scale of 1 meter, and tried to load it using OBJLoader in Three.js. However, even though there are no errors, the model is not showing up. What could be causing this problem?

<script src="http://threejs.org/build/three.js"></script>
<script src="http://threejs.org/examples/js/loaders/OBJLoader.js"></script>
<body style="margin:0;padding:0;">
</body>
<script>
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 1, 2000);
    var render = new THREE.WebGLRenderer();
    camera.position.set(0, 0, 53);

    render.setSize(innerWidth, innerHeight);
    document.body.appendChild(canvas = render.domElement);

    render.setClearColor(0x111111, 1);

    function loadScene() {
        var loader = new THREE.OBJLoader();
        loader.load("./fox.obj", function(model) {
            model.traverse(function(child) {
                if (child instanceof THREE.Mesh) {
                    child.material.color = 0xffb830;
                }
            });
            model.position.set(0, 0, -53);
            scene.add(model);
            window.model = model;
        });
        render.render(scene, camera);
    }

    window.onload = loadScene;
</script>

Answer №1

I managed to get it working by implementing the following steps:

1 - I removed the line below:

render.render(scene, camera);

2 - Then, I added this code snippet after setting up the initializations:

function animate() {
    requestAnimationFrame( animate );
    render.render( scene, camera );
}
animate();

3 - Furthermore, I utilized a different source for the three.js library. I incorporated the local copy that is currently functioning in another project, and it resolved the issue. It's possible that you are retrieving it from an outdated source... Consider obtaining the file directly from the download link: https://github.com/mrdoob/three.js/archive/master.zip

It is also advisable to integrate OrbitControls into the scene so that you can navigate around the object, especially if it may be larger than expected and not visible as a result.

var controls = new THREE.OrbitControls( camera, render.domElement );

UPDATE:

To address the issue, simply call the render function within the loader's method, as suggested by ManoDestra:

loader.load("./fox.obj", function(model) {
    model.traverse(function(child) {
        if (child instanceof THREE.Mesh) {
            child.material.color = 0xffb830;
        }
    });
    model.position.set(0, 0, -53);
    scene.add(model);
    window.model = model;
    render.render(scene, camera);
});

Answer №2

If you're encountering an issue, it might be because you are trying to render the scene before the object is fully loaded.

To fix this, make sure you place your render.render(scene, camera) call after your model has finished loading. Here's an example:

function loadScene() {
    var loader = new THREE.OBJLoader();
    loader.load("./fox.obj", function(model) {
        model.traverse(function(child) {
            if (child instanceof THREE.Mesh) {
                child.material.color = 0xffb830;
            }
        });
        model.position.set(0, 0, -53);
        scene.add(model);
        window.model = model;
        render.render(scene, camera);
    });
}

It's also important to ensure that all of your source code is in the head section or at the end of your HTML. Then, trigger your initialization code on the window's load event. Remember, only render the scene once everything is fully loaded.

You may need to adjust the camera position to look at your scene, like so...

camera.lookAt(scene.position);

Lastly, keep in mind that child.material.color is an object e.g.

child.material.color = { r:1, g:1, b:1 }
.

Answer №3

  1. Make sure to use
    THREE.MeshBasicMaterial({color:'red'})
    on all your loaded meshes, ensuring that issues like missing normals, lights, and textures are eliminated effortlessly (This material does not depend on any of those factors to function).
  2. Check the values in
    model.children[N].geometry.vertices
    to ensure they are valid

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

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

Deleting object property within Angular ng-repeat loop

I have information structured like this: $scope.cart={"4": {"cost": 802.85, "description": "test", "qty": 1}, "5": {"cost": 802.85, "description": "test", "qty": 1}}; My goal is to iterate through this data and show it with a remove button. How can I s ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Unraveling the Distinctions: Identifying an Admin vs. a User within the API

When working with the express framework, I encounter a situation where I need to restrict access to certain API endpoints. For example, I have this line in the API: router.delete('/user',(req, res) => { //deleting...} Now, I want only an Adm ...

Challenge with Context Api state not reflecting the latest changes

Hey there, I've got this function defined in AuthContext.js: let [authTokens, setAuthTokens] = useState(null) let [user, setUser] = useState(false) let [failedlogin, setFailedlogin] = useState(false) let loginUser = async (e) => { ...

The hyperlink element has been added but is not clickable

I'm attempting to incorporate a download feature into my webpage using Greasemonkey. Despite successfully adding the new div element to the page, I am encountering an issue where the download window does not open as expected. var iDiv = document.crea ...

Tips for preventing real-time changes to list items using the onchange method

I am facing an issue with a list of items that have an Edit button next to them. When I click the Edit button, a modal pops up displaying the name of the item for editing. However, before clicking the save button, the selected item in the list gets changed ...

Executing several GET requests in JavaScript

Is there a more efficient way to make multiple get requests to 4 different PHP files within my project and wait for all of them to return successfully before appending the results to the table? I have tried nesting the requests, but I'm looking for a ...

Guide to arranging components in two columns using VueJS Vuetify Grid

My goal is to align two components in order to display data on two columns. I followed the official Vuetify Grid tutorial, but encountered some issues with fixed row components. Despite trying to change from row to column, it still doesn't work as exp ...

Monitor the elements displayed as you scroll

Thank you for taking the time to read this. I am currently working on a webpage that features a top Calendar component displaying a week, and below that is a Scroll component showing detailed information for each day of the week. Here is what my page loo ...

Are you familiar with the Puppeteer PDF tool that generates empty pages from the cloud and seamlessly integrates with Postman? What do

After days of searching, tweaking, and deploying, I still can't get this to work. I'm hoping it's just a simple mistake on my part that someone else can help me with. I am attempting to use Puppeteer to generate a PDF from a Node.js Express ...

Showing Variables in JavaScript

<!DOCTYPE HTML> <html> <body> <button onclick="question++">Increment</button> <script> function test() { var question = 0; } </script> </body> </html> Qu ...

Stop dishonesty in a timed internet assessment

At my company, we frequently host online competitions that involve simple multiple-choice quizzes. The winner is determined by the fastest completion time. Lately, we have been facing a major issue with cheaters submitting quiz entries in less than one se ...

How can I incorporate the GroundProjectedSkybox object from three.js into an AFrame project?

Recently, I discovered a technique in three.js that allows for the creation of a ground-projected environment. Now, I am eager to implement this feature into my AFrame project. Since AFrame is built on top of three.js, I believe it should be possible to le ...

broker handling numerous ajax requests simultaneously

Is there a way to efficiently handle multiple simultaneous ajax calls and trigger a callback only after all of them have completed? Are there any JavaScript libraries available that can manage numerous ajax calls to a database at the same time and execute ...

Implementing html5mode in Express.js and Angular.js for cleaner URLs

I've been working on resolving the issue of avoiding # in my Angular app with an ExpressJS server-side setup. I found a solution to enable html5mode and it worked well. However, whenever there is another 'get' request to fetch data from a di ...

Is there a way to apply a smooth fade-in effect to an object using Three.js animations?

I'm exploring Three.js for the first time and I'd love to implement a fade-in animation when adding a new mesh geometry to my scene. Specifically, I want the material's opacity to smoothly transition from 0 to 1 upon addition. Can anyone gui ...

The Autocomplete feature from the @react-google-maps/api component seems to be malfunctioning as it returns

I'm encountering some difficulties with the Autocomplete component in @react-google-maps/api. While Autocomplete is working and displaying options, clicking on an option fills the input box but I'm only getting 'undefined' from the Plac ...

Performance problem with React-Native for-looping through a large array size

I'm currently facing a performance issue with the search function in my react-native app. The search involves scanning through an array of 15,000 elements for specific keywords. Surprisingly, the search performs well and quickly on Android devices, bu ...

Grid Column with Checkboxes in Kendo UI for Vue

Seeking help in adding a checkbox column to a Kendo UI Vue grid. The column should display the values of a boolean field from the grid's data source. While I am aware of how to add a checkbox column for selection as demonstrated here: https://www.tele ...