Include the model.obj file into the three.MESH framework

I am a beginner in three.js and I am developing an augmented reality application on the web to showcase plates of food. Currently, I have successfully displayed a cube. However, when I attempted to display a model.obj instead of using geometry and material in mesh, I encountered an issue. I am struggling to figure out how to incorporate a model.obj in THREE.MESH. Below is my code snippet.

 function createContainer() {
    var model = new THREE.Object3D();
    model.matrixAutoUpdate = false;
    return model;
}

function createMarkerMesh(color) {
       manager = new THREE.LoadingManager();
     manager.onProgress = function (item, loaded, total) {

        console.log(item, loaded, total);

    };
     var texture = new THREE.Texture();
     var loader = new THREE.ImageLoader(manager);
     loader.load(texturePath, function (image) {

      texture.image = image;
      texture.needsUpdate = true;
      texture.transparent = true;

    });

    var loader = new THREE.OBJLoader(manager);
    return loader.load(objectPath, function (object) {

        object.traverse(function (child) {

            if (child instanceof THREE.Mesh) {

                child.material.map = texture;
                child.material.transparent = true;

            }

        });
        object.position.z = -50; 

        return object;
    });

   // var geometry = new THREE.CubeGeometry( 100,100,100 );
   //var material = new THREE.MeshPhongMaterial( {color:color, side:THREE.DoubleSide } );
    var mesh = new THREE.Mesh( object.geometry, object.material);                      
    mesh.position.z = -50;

   return mesh;
}



function createMarkerObject(params) {
 //return   createMarkerMesh(params.color);
 var modelContainer = createContainer();
 var modelMesh = createMarkerMesh(params.color);
 console.log(modelMesh);
 modelContainer.add( modelMesh);

    function transform(matrix) {
        modelContainer.transformFromArray( matrix );
    }

    return {
        transform: transform,
        model: modelContainer
    }
  return {
    createMarkerObject:createMarkerObject
}

}

The portion of code within the CreateMarkerMesh function successfully generated a cube. However, after commenting out those sections and attempting to display an object, nothing seems to be working as expected. Please assist me in resolving this issue.

Answer №1

Give this modification a try in your script... Notify me if any issues arise.

function generateMarkerMesh(color) {
   manager = new THREE.LoadingManager();
   manager.onProgress = function (item, loaded, total) {
   console.log(item, loaded, total);
 };
 var texture = new THREE.Texture();
 var loader = new THREE.ImageLoader(manager);
 loader.load(texturePath, function (image) {

  texture.image = image;
  texture.needsUpdate = true;
  texture.transparent = true;

});
var tmpMesh;
var loader = new THREE.OBJLoader(manager);
loader.load(objectPath, function (object) {
var group = new THREE.Object3D()
object.traverse(function (child) {
    if (child instanceof THREE.Mesh) {
        child.material.map = texture;
    child.material.transparent = true;
        //inside child, both geometry and material are accessible
        var mesh = new THREE.Mesh( child.geometry, child.material);
        //mesh.position.z = -50;
        group.add(mesh);
    }
});
group.position.z = -50;
scene.add(group);//return group;
});
}

Answer №2

After much searching, I have finally cracked the code and figured out a solution to the problem at hand. Allow me to elucidate on what exactly was causing the issue with the code above. Hopefully, this explanation will prove useful.

The root of the problem lied in the premature invocation of createMarkerObject before the mesh had even been created. This led to the object3D container being populated with an empty mesh. To rectify this issue, I decided to declare the modelContainer as a global variable and embed it within the createMarkerMesh function. Additionally, I added an if statement inside createMarkerObject to ensure that the modelContainer is not empty before adding it to the object3D container. Below, you'll find the revised code snippet.

// Function that loads the model and texture, creates a mesh, and returns the mesh
function createMarkerMesh() {
    manager = new THREE.LoadingManager();
    manager.onProgress = function (item, loaded, total) {
        console.log(item, loaded, total);
    };
    
    var texture = new THREE.Texture();
    var loader = new THREE.ImageLoader(manager);

    loader.load(texturePath, function (image) {
        texture.image = image;
        texture.needsUpdate = true;
        texture.transparent = true;
    });

    var tmpMesh, mesh;
    var loader = new THREE.OBJLoader(manager);

    loader.load(objectPath, function (object) {
        tmpMesh = object; // Store the object in a variable
        
        object.traverse(function (child) {
            if (child instanceof THREE.Mesh) {
                child.material.map = texture;
                child.material.transparent = true;
            }
        });

        mesh = new THREE.Mesh(tmpMesh.children[0].geometry, tmpMesh.children[0].material);
        mesh.position.z = -10;
        mesh.scale.set(3, 3, 0);
        console.log(mesh);
        modelContainer.add(mesh);
        console.log(modelContainer);
    });
} 

// Function that defines the position of the object on the marker
function createMarkerObject() {
    modelContainer = createContainer();
    var modelMesh = createMarkerMesh();

    if (modelMesh){
        modelContainer.add(modelMesh);
    }

    function transform(matrix) {
        modelContainer.transformFromArray(matrix);
    }

    return {
        transform: transform,
        model: modelContainer
    };

    return {
        createMarkerObject: createMarkerObject
    };
}

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

JavaScript believes that the function is not defined, despite its clear existence

This question pertains to an issue regarding the recognition of Bookshelf.js model function as a function. The error message "Function is undefined, Bookshelf.js model function is not being recognized as a function" arises when trying to POST to the login ...

Executing an external HTTP request within an ExpressJS middleware prior to rendering the response

Currently, I am facing a challenge while trying to utilize Express middleware for a login request. The default route generates an external URL that redirects to /login?code={login-code}. This URL triggers an external HTTP request to obtain the user_id and ...

What is the preferred convention for defining AngularJS directives as "attributes" versus "elements"?

When creating Angular directives, I've noticed that some directives could also be defined as either an HTML element or an attribute. I'm curious to know what the community convention is for choosing between the two, and the reasons behind it. Fo ...

The reactjs-toolbox radio button group remains unchanged

In my React application, I have implemented radio buttons using the following code: <RadioGroup name='steptype' className={css.ProcessStepRadioButtons} value={this.state.stepsData[stepNumber].stepType} onChang ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

Prevent individual elements from shifting around on browser resizing within a React form

Having issues with a React form that includes an image gallery and input fields. import React, { Component } from 'react'; import ImageGallery from 'react-image-gallery'; import { Container, Row, Col, InputGroup, Button, FormControl, ...

Utilize jQuery Function on Identical Class of <ul> Elements

I have integrated a listview control in my ASPX page. The data is being fetched from the database and displayed in the listview. I have also utilized jQuery script to implement the .fadein() and .fadeout() effects on the listview elements. However, when I ...

What is the most effective way to dynamically incorporate external input into a SlimerJS script?

Could use some assistance with SlimerJS. My current program requires intermittent input from stdin to proceed with the next task. The code below functions effectively when using PhantomJS+CasperJS for reading external input, but encounters difficulties wi ...

Learn how to properly register the order of checkboxes in AngularJS

I have a unique requirement for my webapp where I need to display the order in which checkboxes are checked. I came up with the following code to achieve this functionality: $scope.updateNumbers = function(id, checked, inputs) { if (checked === true) ...

Leverage JavaScript to retrieve content and generate an iframe

Can you use JavaScript to extract and insert <div> content from another website into the current site? For example: If Website 1 has a portal and wants to include content from Website 2. Website 2 contains the required content within the <div i ...

Tips for implementing custom fonts in NextJS without relying on external services

Utilizing Fonts in NextJS I have been researching various methods for using self-hosted fonts with NextJS. When attempting the following code, I encountered a [ wait ] compiling ...: @font-face { font-family: 'montserrat'; src: url(&a ...

Changing Underscores in ES6 Techniques

My current project is built using AngularJS, Redux, and Underscore. Within this project, I have the following code snippet: const selectedBroker = _.findWhere(state.brokers, { brokerId: action.payload }); return state.merge({ selectedBroker, sel ...

Error message encountered: "Node.js Object [object Object] does not support the method"

My application uses Express.js and mongodb, including the mongodb Native driver. I have created a model with two functions for retrieving posts and comments: // Retrieve single Post exports.posts = function(id,callback){ MongoClient.connect(url, fun ...

adding numerous items to an array using JavaScript

How can I add multiple objects to an array all at once? router.post(`/products`, upload.array("photos" , 10), async (req, res) => { console.log(res); try { let product = new Product(); req.files.forEach(file => { product.p ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

Is there a way in Jquery to retrieve the id of the clicked element and modify its name?

I am using a drag-and-drop website builder that utilizes HTML blocks, each with a unique ID. After dropping the blocks onto the canvas, I want to create a navigation menu that links to the IDs of each block. How can I retrieve the current ID of the block I ...

Tips for passing a function and an object to a functional component in React

I am struggling with TypeScript and React, so please provide clear instructions. Thank you in advance for your help! My current challenge involves passing both a function and an object to a component. Let's take a look at my component called WordIte ...

Converting a Number from Negative to Positive in JavaScript and Representing it as 32 Bit Binary

I am facing an issue with converting a number to 32-bit binary data. While converting to 16 or 8 bits works fine, the result is incorrect when attempting to convert to 32 bits. For example, for 8 bits: -1 & 255 //result -> 255 or -1 & 0xFF //r ...

When a base html tag is dynamically added, the browser mistakenly loads assets twice

When managing relative paths on a website, I utilize the <base> tag within the <head> section of each page. Although all resources loaded via relative-like paths in the documents are displayed correctly, my observations show that browsers such ...

Show all column data when a row or checkbox is selected in a Material-UI datatable

I am currently working with a MUI datatable where the properties are set as below: data={serialsList || []} columns={columns} options={{ ...muiDataTableCommonOptions(), download: false, expa ...