Guide for displaying an image exclusively on the front side of a JSON model object using Three Js

Hey there, I've been working on rendering an image onto a model object using a JSON file. While I've successfully rendered the model itself, I'm facing an issue with getting the image to render from the JSON file.

var loader1 = new THREE.AssimpJSONLoader();
loader1.load(modelUrl, function(assimpjson){
                                // console.log(assimpjson.geometry);
                                assimpjson.traverse(function(child){
                                        if(child instanceof THREE.Mesh) {
                                                // newMesh = new THREE.Mesh(assimpjson, mat);
                                                object_json = assimpjson;
                                                assimpjson.traverse(function(child) {
                                                        if(child instanceof THREE.Mesh){
                                                                // I am able to set the color of the child 
                                                                // but how can i set the image on the model?
                                                                // I tried loading the image like this 
                                                                // var image = new THREE.TextureLoader().load('assets/images/image1.jpg');
                                                                // Is there a way than i can directly set the image to the mesh child in here 
                                                                // and give a custom height and width to the image.
                                                                // child.material.color.setHex(0xFFFFFF);
                                                        }
                                                });
                                                assimpjson.scale.x = 30;
                                                assimpjson.scale.y = 30;
                                                assimpjson.scale.z = 30;
                                                assimpjson.position.x = 120;
                                                assimpjson.position.y = -200;
                                                assimpjson.position.z = 0;
                                                assimpjson.updateMatrix();
                                                if (previous) scene.remove(previous);
                                                scene.add(assimpjson);
                                                previous = assimpjson;
                                        }
                                });
   });

Any assistance on this would be greatly appreciated! Thanks a lot!!!

Answer №1

How about trying this out? -

function load_custom_model(modelUrl, texture) {

    var custom_loader = new THREE.AssimpJSONLoader();
    custom_loader.load(modelUrl, function (assimpModel) {
        custom_object_json = assimpModel;
        if (texture) {
            assimpModel.traverse(function (child) {
                if (child instanceof THREE.Mesh && child.material) {
                    child.material.map = texture;
                    child.material.needsUpdate = true;
                }
            });
        }

        assimpModel.scale.x = 30;
        assimpModel.scale.y = 30;
        assimpModel.scale.z = 30;
        assimpModel.position.x = 120;
        assimpModel.position.y = -200;
        assimpModel.position.z = 0;
        assimpModel.updateMatrix();
        if (old_model)
            scene.remove(old_model);
        scene.add(assimpModel);
        old_model = assimpModel;
    });
}


// use a loader
let custom_texture_loader = new THREE.TextureLoader().load("path", function (texture) {
        load_custom_model(modelUrl, texture);
    },
    // Show progress during download
    function (xhr) {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded');
    },
    // Handle download errors
    function (xhr) {
        console.log('Oops! An error occurred');
        load_custom_model(modelUrl);
    });

Answer №2

To add texture to specific triangles on your model, you can use a THREE.MultiMaterial (an array of materials) MultiMaterial (no longer available)

Depending on whether your loader creates Geometry or BufferGeometry, you will need to assign the desired material ID to each triangle of your model.

For BufferGeometry, you can set up BufferGeometry.groups with { start: Integer, count: Integer, materialIndex: Integer }

For Geometry, you need to assign an integer to each Geometry.faces for Face3.materialIndex

I hope this explanation helps!

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 for converting a CSV file to JSON format using node.js?

I am working on converting a CSV file from Clash Royale into an array. The CSV file has over 40 properties in its header or data. For example: name level count upgrade cost common 14 5, 20, 50, 100 rare 12 50, 150, 400, 1000 Below is my node.j ...

Troubleshooting: Angular 6 Renderer2 Issue with Generating Dynamic DOM Elements for SELECT-Option

Currently, I am attempting to dynamically create a select option using Renderer2. Unfortunately, I am facing difficulties in creating the <Select></Select> element, but I can confirm that the <options> are being successfully created. Due ...

What is the best method for incorporating multiple jQuery ready() functions?

Trying to develop a web application with HTML files that require multiple JS files. Need to specify tasks inside jQuery.ready() in each JS file, but unable to define $(function () {}) more than once. Is there a way to modify the passed function? index.pug ...

The disappearance of the overlay background due to modal reload in NextJS dynamic routing

I am working on a simple NextJS app where clicking on a page opens a modal with updated URL but without triggering a new navigation. The content inside the modal is displayed, while the actual page location is reflected in the URL and refresh takes the use ...

Accessing a specific attribute of an object contained within an array

Currently, I am utilizing Vue.js in my project and have implemented a method that involves comparing values from two different arrays. array1: [{ name: 'test1', somevar: true }, { name: 'test2', somevar: false }] array2: ['test1 ...

Error encounter when loading the chunk for FusionCharts's overlappedbar2d.js in React.js: fusioncharts.overlapped

Currently, I am working on a web application that utilizes next.js and FusionCharts. Within the app, various FusionChart types have already been set up. My task now is to integrate the Overlapping Bars chart as outlined in the following documentation: How ...

Getting the number of ticks from an rxjs Observable is a simple process that involves extracting

Is there a way to track how many times this observable has run? this.clock = Observable.interval(1000).map(function(value){ if(value == 0){ return value * 100 / 60; } return value * 100 / 60; }).take(61); I would like to kno ...

Total of Vue Component Subtotals

One of the challenges I'm facing in my Vue app is calculating the total of subtotals. Every component has its own subtotal that depends on user input. I need to combine these individual subtotals and display the result in an input field outside of th ...

Using the novalidate attribute in Angular 4.0.0

Since migrating to angular 4, I have encountered a peculiar issue with my template-driven form. The required attribute on the input field appears to be malfunctioning. It seems like the form has the novalidate attribute by default, preventing HTML5 validat ...

React Router imports and renders multiple components

I'm currently working on developing a basic Login System. When I try to register, both components are loaded into the App Component. Here is my code: class App extends React.Component { render() { return ( <div className="row"> ...

Removing borders from textField in ReactJS can be achieved using a combination of CSS

Is there a way to remove the border from a TextField component? <Box display="flex" alignItems="center" border="1px solid #ccc" borderRadius="4px" paddingLeft="10px"> <Typography variant=&quo ...

Issue with initializing MdTable in Vue Material when fetching data

After encountering a null error while trying to fetch remote data to initialize the MdTable component, I shared my issue here. The data is retrieved from a MySQL database as part of a Laravel 5.6 API project. Upon thorough investigation, it seems that the ...

An issue arises when trying to group and sum an array of objects due to difficulty converting strings to arrays in TypeScript

Below is the provided code snippet: Definition of Interface - interface IWEXInterface { readonly Date?: string; "Exec Qty"?: string; readonly Expiry?: string; } Data Collection - let data: IWEXInterface[] = [ { Date: &qu ...

Guide on uploading multipart career-form data with file paths and validation in CodeIgniter with the help of AJAX

I am facing an issue while attempting to insert job form data with file uploading and validation in PHP CodeIgniter via AJAX. The code I am using is provided below, but unfortunately, it's not functioning as expected. Can anyone help me figure out how ...

Retrieving the return value from an AJAX call in C# using asynchronous methods

When it comes to retrieving a value using Ajax on the client side, I rely on this JQuery function: $.ajax({ type: "POST", url: "/my-page.aspx/checkout", contentType: "application/json; charset=utf-8", dataType: "json", success: functio ...

Can the vertex displacement through textures in Three JS be restricted to only 256 values?

Utilizing Ashima's GLSL noise, I am applying the texture shown below to a WebGLRenderTarget in ThreeJS: https://i.sstatic.net/mSiYd.jpg To displace vertices in several meshes along the XYZ axes, I am extracting the RGB channels from the texture and ...

The AJAX requests in my project are failing to trigger upon touch events when using the jQuery Plugin

Ensuring that both <script src="hammer.js"></script> and <script src="../jquery.hammer.js-master/jquery.hammer.js"></script> have been correctly included in my header. I have a mouse click-triggered AJAX event for dynamic and depen ...

What is the method for nesting data within a component's child>child>child structure?

In the structure I am working with, there is a hierarchy: Root component buttons (menu search component) - an input field for searching Widgets (widget component ) (Cats widget) - displays what is input in the menu search here. My challen ...

Attempting to send data as arguments in an axios request

I have been working on setting up a forum and I want to implement a feature where clicking on a post title will take the user to a page I've already created that displays the title and body of the post. I utilized MUI for building the page, but I enco ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...