Enhancing the visual appeal of a JSON object with texture using Three.js

Struggling to apply texture to my 3D Dog JSON model exported from clara.io. Tried using Objectloader and Textureloader, but the texture won't load onto the model.

The code might be incorrect or in the wrong place. Looked at other examples but no luck. The main issue is the texture not appearing on the model, and there are no errors in the console either.

If anyone can offer assistance, it would be greatly appreciated.

 <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>three.js webgl - loaders - Clara.io JSON loader</title>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
            <style>
                body {
                    font-family: Monospace;
                    background-color: #000;
                    color: #fff;
                    margin: 0px;
                    overflow: hidden;
                }
                #info {
                    color: #fff;
                    position: absolute;
                    top: 10px;
                    width: 100%;
                    text-align: center;
                    z-index: 100;
                    display:block;
                }
                #info a, .button { color: #f00; font-weight: bold; text-decoration: underline; cursor: pointer }
            </style>
        </head>

        <body>

            <script src="three.js"></script>
            <script src="Detector.js"></script>
            <script src="stats.min.js"></script>
            <script src="UnpackDepthRGBAShader.js"></script>
            <script src="ShadowMapViewer.js"></script>
            <script src="dat.gui.min.js"></script>
            <script src="OrbitControls.js"></script>

            <script>
                var container, stats;
                var camera, scene, renderer;
                var mouseX = 0, mouseY = 0;
                var windowHalfX = window.innerWidth / 2;
                var windowHalfY = window.innerHeight / 2;
                init();
                animate();
                function init() {
                    container = document.createElement( 'div' );
                    document.body.appendChild( container );
                    camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
                    camera.position.z = 4;
                    // scene
                    scene = new THREE.Scene();
                    var ambient = new THREE.AmbientLight( 0x444444 );
                    scene.add( ambient );
                    var directionalLight = new THREE.DirectionalLight( 0xffeedd );
                    directionalLight.position.set( 0, 0, 1 ).normalize();
                    scene.add( directionalLight );

                    //new attempt at a texture and object loader
                    var loader = new THREE.TextureLoader();
                    loader.load("dogtexture.jpg", function ( texture ) {
                        var material = new THREE.MeshBasicMaterial({ map: texture });
                        var objectLoader = new THREE.ObjectLoader();
                        objectLoader.load( "blue-dog1.json", function( obj, texture ) {
                            obj.scale.set( .04, .04, .04);
                            scene.add( obj,texture );
                        });
                    });


                    // BEGIN Clara.io JSON loader code
                    //var objectLoader = new THREE.ObjectLoader();
                    //objectLoader.load("blue-dog.json", function ( obj ) {
                    //obj.scale.set( .045, .045, .045);
                     //scene.add( obj );
                    //});

                    //var loader = new THREE.TextureLoader();
                    //loader.load("dogtexture.jpg", function ( texture ) {
                    // do something with the texture
                    //var material = new THREE.MeshNormalMaterial( {    map:          //texture} );
                    //} );

                    // END Clara.io JSON loader code
                    renderer = new THREE.WebGLRenderer();
                    renderer.setPixelRatio( window.devicePixelRatio );
                    renderer.setSize( window.innerWidth, window.innerHeight );
                    container.appendChild( renderer.domElement );

                }

                //
                function animate() {
                    requestAnimationFrame( animate );
                    render();
                }
                function render() {
                    camera.position.x = 400;//vertical camera angle
                    camera.position.y = 300;
                    camera.position.z = 150;

                    camera.lookAt( scene.position );
                    renderer.render( scene, camera );
                }
            </script>

        </body>
    </html>

Answer №1

MeshNormalMaterial may not be the most suitable material type for your needs.
Consider using MeshBasicMaterial or MeshPhongMaterial.

You can find more information on MeshNormalMaterial from here.

This material maps normal vectors to RGB colors.

Take a look at the various types of materials available on the left side of the three.js docs.

EDIT..
You forgot to add the material onto the object..

EDIT..
Here's an example code snippet. If ObjectLoader is working for you, this should help.

// Create material for future use.
var material = new THREE.MeshBasicMaterial();
// Create ObjectLoader.
var objectLoader = new THREE.ObjectLoader();
// Load model
objectLoader.load("blue-dog1.json", function(obj) {
  // Traverse children and apply material (assuming it's an Object3D).
  obj.traverse(function(child) {
    if(child instanceof THREE.Mesh) {
      child.material = material;
    }
  });
  // Add loaded object to scene after applying material.
  scene.add(obj);
  // Load texture.
  var loader = new THREE.TextureLoader();
  loader.load("dogtexture.jpg", function(texture) {
    // Apply texture to material.
    material.map = texture;
    // Update material.
    material.needsUpdate = true;
  });
});

This code is a starting point, though untested. If you encounter issues, consider searching for examples with JSONLoader class.

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

Iterate through a listbox and append the content to a textbox using JavaScript

I am currently working on a script to read all the data from a listbox and populate a textbox with those values. I initially attempted to use a for loop for this task, but it seems to be running only once and then stopping. var listbox = $('#<%=l ...

Is it within the realm of possibility for a route-handling function to accept more than two parameters?

Recently, I started learning about node js and delved into the world of jwt authentication. While going through some code snippets, I came across a request handler in express that caught my attention. app.post('/login',function(req,res){...}); ...

Is there a more effective method for merging two JSON files in Python?

Two json files with the same structure are available. The json entries do not have nesting, and they consist of strings as keys and integers as values. I am looking to merge both json files into a single file by concatenating them. There may be instances w ...

The light/dark mode toggle is a one-time use feature

I've been experimenting with creating a button to toggle between light and dark modes on my website. Initially, it's set to light mode, but when I try switching to dark mode, it works fine. However, the issue arises when attempting to switch back ...

Sending Ajax data to a controller function

I am looking for guidance on how to pass values from my view to my controller using ajax. As someone who is new to working with ajax, I would appreciate some assistance in understanding the process. Full Page @model ALSummary.Models.MonthReport @{ ...

enhanced labeling for checkboxes in Vuetify

Below is a snippet of my straightforward code: <v-checkbox v-model="rodo" label="I consent to Terms and Conditions (click for more info)" :rules="termsRules" required ></v-checkbox> I am looking to keep the label simple with an option ...

The Vue application is unable to expand to 100% height when using a media query

Hello everyone, I'm currently using my Vue router for multiple pages, and I'm facing an issue where setting the height of the main container to 100% within this media query is not working as expected: @media screen and (min-width: 700px) { #sig ...

Discovering documents using the outcome of a function in mongoose

Hey there, I have a scenario with two schemas known as user and driver, both containing latitude and longitude attributes. My goal is to search the database for nearby drivers based on the user's current location (latitude and longitude) using a custo ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

Loading JavaScript asynchronously using ExtJS

I have created a custom widget using the ExtJS framework. In order to load the necessary ext-all.js script asynchronously, I wrote an embedd.js script that also combines other JavaScript files. I've attached a function to be called when Ext.onReady is ...

Begin a new countdown timer upon clicking the next button

Currently, I am developing a bid auction website and I have implemented a countdown timer script. The timer works perfectly on the initial window load. However, when I click on the restart button, it fails to reset the countdown timer to a new value. < ...

Creating a 3D model by superimposing a map onto a DTM and exporting it as a

Seeking advice on how to overlay a map onto a DTM (digital terrain model) or DEM. I've already attempted using QGIS plugins openLayers and QGIS2Threejs, but the 3D model export doesn't include UV mapping which causes issues with textures when loa ...

Ways to increase the value of a key by combining it with another in a Hash Map when there are duplicate keys

Trying to insert JSON data into a HashMap that may have multiple duplicate keys. Here's an example: { "member Detail": { "firstname": "John", "lastName": "Doe", "Address": "Los Angeles", "Email": "<a href=" ...

Here's a unique version: "Verify if the searched location matches the corresponding data in the API and notify the user with an alert in case of any discrepancies."

Currently, if a user doesn't input a valid location in the API (e.g. a spelling mistake), the console displays an error. How can I make an alert appear on the screen to notify the user when this happens? const cityRef = document.querySelector(&ap ...

Mastering the art of handling errors with Javascript Promises

Through thorough research and some assistance, I have managed to create and annotate code that I believe will enhance the comprehension of Javascript Promises for individuals. However, I encountered a puzzling issue when attempting to trigger an error by ...

Rails is generating unexpected JSON responses when used with Objective-C's NSArray

I've been developing an API using Rails and Objective-C. On the Objective-C side: NSLog(@"NSArray: %@", allPosts); It seems like there might be an issue on my Rails side. I was expecting a response like this: { id: 1, galleries: [ ...

unable to retrieve the value from the scope

I'm trying to implement the following code in HTML: <div ng-if="item.shareText"> <textarea></textarea> <div> <select ng-model="shareOptions"> <option value="PUBLIC" selected>public</option> ...

extract specific data from JSON using JavaScript

Dealing with JSON data can be tricky, especially when working with multiple sets of information to choose from. When I inspect the data in my JavaScript code using console.log(contacts.data["all"]);, I can see the returned objects clearly. Here's a ...

Express middleware for serving static files using express.static() is not properly handling routing and is throwing an error stating that next()

During the development and testing phase on my local machine, everything was working as expected. However, once deployed to our UAT environment using Docker, I encountered some issues that are puzzling me: next() is not a function Another problem I'm ...

Issue encountered with input form containing a JSON field in Rails version 4.2

Within my Rails 4.2 application utilizing a postgres database, the field ui_layout has been transformed into json within the database table (utilizing psql's support for the json data type). Previously, the ui_layout field was a text field. However, u ...