Loading objects with textures in Three.js using the objloader

For the past few weeks, I've been diving into Three.js and managed to successfully apply a texture to a cube I created directly in the code. However, when I attempted to load an OBJ file using OBJLoader, I ran into issues trying to load simple png or jpg textures with TextureLoader.

Now, I'm unsure of what exactly is going wrong. I'm not sure if this is the correct method, if I can't load a basic image properly, or if I'm simply applying it incorrectly.

I've noticed that applying a texture with an MTL file appears to be straightforward, but unfortunately, I'm not familiar with how to create one.

The current snippet of my code looks something like this:

        var loader = new THREE.OBJLoader( manager );
        loader.load( 'models/tshirt.obj', function ( object ) {

            object.position.x = 0;
            object.position.y = -200;
            object.scale.x = 10;
            object.scale.y = 10;
            object.scale.z = 10;
            obj = object;
            texture = THREE.TextureLoader('img/crate.png'),
            material = new THREE.MeshLambertMaterial( { map: texture } );
            mesh = new THREE.Mesh( object, material );
            scene.add( mesh );

        } );

Unfortunately, this approach doesn't seem to work as expected. The model fails to load and instead throws random errors from Three.js. Interestingly, if I replace scene.add( obj); with scene.add( mesh);, the model actually loads.

What should I do next? Should I attempt to create an MTL file?

You can view my complete working code at

EDIT: When adding mesh instead of obj, I encounter the following error:

three.min.js:436 Uncaught TypeError: Cannot read property 'center' of undefined

Answer №1

Check out this code snippet for loading and applying textures:

const OBJFile = 'assets/model.obj';
const MTLFile = 'assets/model.mtl';
const JPGFile = 'assets/texture.jpg';

new THREE.MTLLoader().load(MTLFile, function (materials) {
    materials.preload();
    new THREE.OBJLoader()
        .setMaterials(materials)
        .load(OBJFile, function (object) {
            object.position.y = -95;
            const texture = new THREE.TextureLoader().load(JPGFile);

            object.traverse(function (child) { 
                if (child instanceof THREE.Mesh) {
                    child.material.map = texture;
                }
            });
            scene.add(object);
        });
});

You can find more information about applying textures on objects loaded by OBJLoader from: How to apply texture on an object loaded by OBJLoader?.

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

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Alexa Account Linking - Error: Account linking credentials are not valid

I've been working on setting up an Alexa skill with account linking. After obtaining the Linking Authorization Code and exchanging it for an Access Token, I attempted to input all the necessary parameters: code, access token, and skill ID into the Ale ...

A React child error has occurred in Next.js due to invalid objects being used

Within my project, I have integrated the latest version of next.js and encountered an issue where objects are not valid as a React.js child. https://i.stack.imgur.com/MCO7z.png The problem arises after importing the Head component from Next.js and implem ...

Is there a way to retrieve the name of a JSON or obtain the file path using NodeJS Express Router?

I've been experimenting with adding a named routers feature to the Express router for my NodeJS project. I managed to implement it successfully, but there's one thing I'm stuck on... the path. Specifically, when I have a route setup like thi ...

The click event triggered by the onclick clone/function may not always activate the click handler

As a newcomer in the JavaScript domain, I am encountering an issue where the first clone created after clicking 'add more' does not trigger my click me function. However, every subsequent clone works perfectly fine with it. What could be causing ...

How can I swap a string for a symbol in JavaScript?

Is there a way to convert the text @abc some text here to <a href="some_url">@abc</a> some text here using JavaScript? Are there any libraries that can help with this task? ...

Is it possible to use multiple schemas for one collection name?

I am currently working on creating different schemas for a single collection, such as User or subUser. I aim to store both User and subuser data in the same collection but with different schemas. Here is an example of my schema file: export const AryaSchem ...

Error message while running jQuery 3.2.1: issues with UL and LI

I have a link that displays the desired outcome Despite using jquery version 3.2.1, when I insert my code into Dreamweaver cc 2018, it fails to work. On my jsfiddle, the selection is sorted alphabetically, but on my web page it is not. var mylist = $( ...

Arranging the data in my JSON reply

{ "JsonResult": { "List": [{ "Subject": "Something", "Type": 0, "TypeDescription": "Referral" }], } } When I hit my service, I receive a sample JSON response. After that, there is a button with ...

What is the best way to tally jsonObject instances within the same array based on their id or value

I have a jsonDataArray that contains two nested arrays with objects. My goal is to calculate the number of "duty" parentIds based on the teams' "value" as they have a one-to-one match. For instance, Team A with a value of 500 will have duties such as ...

Childnode value getting replaced in firebase

Every time I attempt to push values to the child node, they keep getting overridden. How can I solve this issue and successfully add a new value to the child node without being overwritten? ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

Can a before hook ever run after a test in any situation, Mocha?

My before hook runs after the initial test and at the conclusion of the second test. Here is the code for my before hook: before(function () { insightFacade.addDataset("courses", content) .then(function (result: InsightResponse) { ...

Utilizing Jquery for independently blinking text counters

Whenever the user presses a button, a message is created and blinks 5 times. However, each time the button is pressed, all previous messages also blink along with the new one. The goal is to make only the new message blink individually 5 times upon each bu ...

Unable to transmit Props to Component - Fluctuating Behavior

I developed a React.js and Next.js application where I needed to pass the User object to all pages. My plan was to then pass this User component to the Head component in order to display different navigation options based on the user's role. Here is w ...

Issues with managing multiple user sessions in express-session

I've been struggling with an issue for a few days now and haven't been able to find a solution. I've scoured forums and documentation, but nothing seems to work. I have a website built in Node.js, using express-session and passport for sessi ...

Rails - removing list item upon deletion of parent object

Currently working on a project app as part of a full stack developer bootcamp program. One of the features I'm implementing is a destroy method to remove an item from a list. Using AJAX requests, the goal is to dynamically remove the li element repres ...

The default action is not triggered when the click event occurs

Hey there, I have been working on this <ol> list of events using jQuery (version 1.4.2). Everything is set up within the $(document).ready() function. Something strange is happening where when I click on the <li>, it triggers a click on the co ...

What are the best methods for detecting devices in order to create customized CSS styles for iPad and Galaxy Tab?

Ensuring my web application is compatible with various devices is crucial. While I have created a common CSS for all mobile and tablet devices, it seems to be causing some problems specifically on the iPad. After finding a fix tailored for the iPad, I now ...

What steps can be taken to confirm the accuracy of input before sending it

Having trouble with validating input before submitting? Every time I run submit(), something seems to be going wrong :( const [value, setValue] = React.useState(""); const [error, setError] = React.useState(""); const validate = () => { value.length ...