The texture failed to load onto the 3D object during the mapping process

Issues with loading texture into the 3D ring model, although it works fine for other objects. No compile errors detected. Proper lighting conditions are set up but the color of the 3D model appears grey/black. The texture loads correctly for other objects. The file format of the 3D object is .obj and I have not loaded the mtl file in my code. Is there a way to load the mtl file and map the texture to the object?

<html>
<head>
<title> Test Three.js</title>
<style type="text/css">
        BODY
        {
            margin: 0;
        }

        canvas
        {
            width: 100%;
            height:100%;
        }



        </style>
</head>
<body>

            <div>
                <p>Color:
                <button class="jscolor{onFineChange:'onClick(this)',valueElement:null,value:'66ccff'}" 
                     style="width:50px; height:20px;"></button>
                    </p>
                    <p>Object:
                        <button style="width:50px; height:20px;" id="object"></button>
                    </p>
            </div>

        <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
        <script src="three.min.js"></script>
        <script src="TrackballControls.js"></script>
        <script src="jscolor.js"></script>
        <script src="AmbientLight.js"></script>
        <script src="SpotLight.js"></script>">
        <script src="JSONLoader.js"></script>">
        <script src="ObjectLoader.js"></script>">
        <script src="OBJLoader.js"></script>">
        <script src="MTLLoader.js"></script>">
        <script src="Material.js"></script>">
        <script src="MeshPhongMaterial.js"></script>">
        <script>
        function onClick(jscolor) {

        cube.material.color = new THREE.Color('#'+jscolor);
        cube.material.needsUpdate = true;
        };

        var onClicked=function (){
            scene.remove(cube);

            var material1 = new THREE.LineBasicMaterial({
                color: 'red'
            });

            var geometry1 = new THREE.Geometry();
            geometry1.vertices.push(
                new THREE.Vector3( -10, 0, 0 ),
                new THREE.Vector3( 0, 10, 0 ),
                new THREE.Vector3( 10, 0, 0 )
            );

            var cube1 = new THREE.Line( geometry1, material1 );
            scene.add( cube1);

        };  

        $('#object').click(onClicked);

        var scene =new THREE.Scene();
        var camera=new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,1000);

        var controls =new THREE.TrackballControls(camera);
        controls.addEventListener('change',render);
        var renderer = new THREE.WebGLRenderer( { alpha: true });

        renderer.setSize(window.innerWidth,window.innerHeight);
        document.body.appendChild(renderer.domElement);
        /*var material = new THREE.MeshLambertMaterial({color:'red'});
        var geometry=new THREE.CubeGeometry(100,100,100);
        var cube=new THREE.Mesh(geometry,material);
        scene.add(cube);*/

        camera.position.z=500;
        var light = new THREE.AmbientLight( 0x404040 );
        light.intensity = 0;
        light.position.z=10;
        light.position.y=10;  // soft white light
        scene.add( light );

                     //  }
        //init();

         /* var loader = new THREE.JSONLoader();
        loader.load( 'ring.json', function ( geometry ) {
        var mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );

                        mesh.position.x =500;
                        mesh.position.y =100;
                        mesh.position.z =500;
        scene.add( mesh );

        }); *//*
        var loader = new THREE.ObjectLoader();
        loader.load("ring.json",function ( obj ) {
            THREE.ImageUtils.crossOrigin = '';
      var texture = THREE.TextureLoader("images.jpg");
       //obj.map= texture;
       obj.scale.set (10,10,10);

        obj.traverse( function( child ) {
            if ( child instanceof THREE.Mesh ) {
                child.geometry.computeVertexNormals(); 
                child.material.map=texture;
            }
        } );
             scene.add( obj );
        });*/
    var 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 );

      // You can set the texture properties in this function.
      // The string has to be the path to your texture file.
      loader.load( 'brick_bump.jpg', function ( image ) {
        texture.image = image;
        texture.needsUpdate = true;
        // I wanted a nearest neighbour filtering for my low-poly character,
        // so that every pixel is crips and sharp. You can delete this lines
        // if have a larger texture and want a smooth linear filter.
       // texture.magFilter = THREE.NearestFilter;
        //texture.minFilter = THREE.NearestMipMapLinearFilter;
      } );

        var loader = new THREE.OBJLoader(manager);
        /*var Mloader= new THREE.MTLLoader(manager);
        Mloader.load('ring.mtl',function(object){
            object.traverse( function ( child ) {
          if (child.material instanceof THREE.MeshPhongMaterial ) {
            child.material.map = texture;
          }
        } );
            scene.add( object );
        });*/
      // As soon as the OBJ has been loaded this function looks for a mesh
      // inside the data and applies the texture to it.
      loader.load( 'ring1.obj', function  ( event ) {
        var object = event;
        /*for ( var i = 0, l = object.children.length; i < l; i ++ ) {

            object.children[ i ].material.map = texture;

            console.log("rgr"+ object);
            }*/

        object.traverse( function ( child ) {
          if ( child instanceof THREE.Mesh ) {
            child.material.map = texture;
            console.log("rgr"+ object.children);
          }
        } );

        // My initial model was too small, so I scaled it upwards.
        object.scale = new THREE.Vector3( 25, 25, 25 );

        // You can change the position of the object, so that it is not
        // centered in the view and leaves some space for overlay text.
        object.position.y -= 2.5;
        scene.add( object );
      });



        function render(){

            renderer.render(scene,camera);
        }

        function animate(){
            requestAnimationFrame(animate);
            controls.update();
        }

        animate();

        </script>

</body>
</html>

Answer №1

To start troubleshooting, I recommend checking the ring.obj file to ensure that UV values are applied to all vertexes. UV values dictate how textures are mapped onto a mesh surface, so it is crucial for them to be present on every vertex. If you do not have control over the export process of the ring.obj file, there are ways to generate UVs at load time as discussed in this Stack Overflow thread:

THREE.js generate UV coordinate

It's possible that the issue lies with the ring mesh itself if the texture is displaying correctly on other meshes. Keep in mind that the mesh author may have specific requirements for texture anchors.

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

I am eager to display this JSON data using AngularJS tables

I have JSON file with content about categories, departments, and digital marketing: { "categories":[ { "dept_id":"123", "category_name":"database", "category_discription":"list of database", "current time ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Click the button to save the text to your clipboard with a customized

Can anyone suggest a method for duplicating div text using JavaScript while preserving the style attributes (italics, font family, size, etc.)? My goal is to paste the copied text into Word and have it maintain the same appearance as on the webpage. For e ...

My React higher order component implementation is revealing the protected route momentarily

import { useRouter } from "next/router"; import { useEffect } from "react"; import axios from "axios"; export default (ChildComponent) => { const enhanceComponent = (props) => { const router = useRouter(); co ...

Programmatically show/hide legend items in amCharts 4

The project includes a Line chart with a legend that are initialized in separate containers. Both components are created using a createFromConfig method. <div ref="chartdiv" /> <div ref="legenddiv" /> My goal is to store to ...

Creating a CSS selector element with an index is a useful skill to have when

Currently, I am in the process of developing a test application using Selenium that relies on CSS Selectors or XPath strings. One specific challenge I encountered was testing menu items that only appear upon hovering. When utilizing "Inspect Element" in bo ...

Error encountered while deploying to Heroku: cross-env not detected in Node.js application

As I attempt to deploy my project on Heroku, the following error persists despite all my efforts. Please assist me in resolving this issue: { "name": "storybooks", "version": "1.0.0", "des ...

Clicked button redirects user to the parent URL

When the application is running on page http://localhost:3000/login, clicking a button should redirect to http://localhost:3000/. This is how I attempted it: import React from 'react'; import { Redirect } from 'react-router-dom'; impor ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...

I have encountered an issue with my rows breaking improperly when viewing them in a PDF format, particularly when I include a minus

Whenever I try to view my HTML page in PDF form, I encounter an issue. The problem arises when the numerical values are too large, causing a line break between the minus sign and the values. Here is an example of the HTML page which appears perfectly: ent ...

Loop through a variable class name in JavaScript

When working with Javascript, I have a series of elements with identical divs: (....loop, where "count" is a unique number for each column) <other divs> <div class="pie"></div> </div> My goal is to be able to rotate each individ ...

What is the best way to implement a function on every item within a specific class?

I'm new to coding and I have a website that showcases job listings. I want to create a function that dynamically changes the logo of a company based on the first 50 characters of the company name mentioned. The current function only works for the firs ...

"Enhance Your Form with Ajax Submission using NicEdit

Currently, I am utilizing nicEditor for a project and aiming to submit the content using jQuery from the plugin. Below is the code snippet: <script type="text/javascript"> bkLib.onDomLoaded(function() { new nicEditor().panelInstance('txt1' ...

What is the best way to stretch the background image across both the footer and navbar for my app?

Here is the code snippet I am currently working with: <template> <v-app> <AppBar></AppBar> <v-main> <router-view></router-view> </v-main> <Footer></Footer> ...

Combining data from an object within an array in JavaScript

I am looking for a way to incorporate values from an Object (weekdayMap) into an existing array (vehicleAvailabilities) that contains objects. I require the value Montag on day one and Dienstag on day two. This pattern continues for each day of the week. ...

iOS alert notification for navigator

How can I fix the issue with my alerts not working on my iOS project? I am using Ionic and AngularJS to develop my app. The problem I am facing is that when the alert pops up, the title shows as "index.html". This is how I call the alert: alert("aaa"); ...

Utilizing JavaScript to conceal div elements within a ul container

How can I hide specific div tags inside a ul tag using JavaScript? All div tags are currently getting hidden when I use the id of the ul tag. However, I need only the first div tag to be shown and the rest to be hidden. Here is the HTML code: <ul clas ...

Acquiring a website's dynamic value using jquery

This question is pretty self-explanatory... I am trying to extract a value from a website's source code, but the value I need is dynamically generated using jQuery. Let's use example.com as an example: <div id="currentTime"></div> ...

Generate an array of identifiers from a pre-existing array

I am facing a challenge where I need to create an array of IDs for each element in an existing array whose size is unknown. The twist here is that every set of four elements should have the same ID. As an illustration, if the original array (let's ca ...

Enable hyperlink to open in a new browser tab after user clicks on button embedded inside an iFrame

<head> </head> <div> <iframe src="https://....."></iframe> </div> https://i.sstatic.net/dk21i.png I'm looking for a way to open the link in a new tab when clicking on this button. Currently, the page loads wi ...