Three.js analyzes the dominant color of an image rather than the image itself

I am experimenting with three.js and trying to apply an image as a texture to an object. However, I am only getting the dominant color of the image instead. I have searched online but couldn't find anyone facing similar issues.

After inspecting the JSON file, I noticed that when using the "mapDiffuse" variable from the code snippet, I still encounter the same problem when applying the texture.

Below is the content of the JSON object file:

{

"metadata" :
{
    "formatVersion" : 3.1,
    "sourceFile"    : "newBox.obj",
    "generatedBy"   : "OBJConverter",
    "vertices"      : 8,
    "faces"         : 6,
    "normals"       : 6,
    "colors"        : 0,
    "uvs"           : 0,
    "materials"     : 1
},

"scale" : 1.000000,

"materials": [  {
    "DbgColor" : 15658734,
    "DbgIndex" : 0,
    "DbgName" : "Material.002",
    "colorDiffuse" : [0.64, 0.64, 0.64],
    "colorSpecular" : [0.5, 0.5, 0.5],
    "illumination" : 2,
    "mapDiffuse" : "test.JPG",
    "opacity" : 1.0,
    "opticalDensity" : 1.0,
    "specularCoef" : 96.078431
}],

"vertices": [1.000000,-1.000000,-1.000000,1.000000,-1.000000,1.000000,-1.000000,-1.000000,1.000000,-1.000000,-1.000000,-1.000000,1.000000,1.000000,-0.999999,0.999999,1.000000,1.000001,-1.000000,1.000000,1.000000,-1.000000,1.000000,-1.000000],

"morphTargets": [],

"morphColors": [],

"normals": [0,-1,0,0,1,0,1,0,0,-0,-0,1,-1,-0,-0,0,0,-1],

"colors": [],

"uvs": [[]],

"faces": [35,0,1,2,3,0,0,0,0,0,35,4,7,6,5,0,1,1,1,1,35,0,4,5,1,0,2,2,2,2,35,1,5,6,2,0,3,3,3,3,35,2,6,7,3,0,4,4,4,4,35,4,0,3,7,0,5,5,5,5]

}

Here is my JavaScript code:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer({alpha:true});
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var mesh;

/**
 * Texture
 */
var texture = THREE.ImageUtils.loadTexture( "/files/test/Three-js-examples-images-crate.jpg" );
var material = new THREE.MeshBasicMaterial( { map : texture } );


// instantiate a loader
var loader = new THREE.JSONLoader();

// load a resource
loader.load(
    // resource URL
    '/files/test/untitled.json',
    // Function when resource is loaded
    function ( geometry ) {
        mesh = new THREE.Mesh(geometry,material);
        mesh.scale.x = 0.8;
        mesh.scale.y = 0.8;
        mesh.scale.z = 0.8;
        scene.add( mesh );
    }
);

camera.position.z = 5;

function render() {
    requestAnimationFrame( render );
    mesh.rotation.x += 0.0001;
    mesh.rotation.y += 0.01;

    renderer.render( scene, camera );
}
render();

This is the outcome I'm experiencing (image stretched from Photoshop):

https://i.sstatic.net/2QmSE.jpg

Below is the image I intend to use:

https://i.sstatic.net/PK9NG.jpg

Answer №1

To add a texture to a model loaded via json, the UVs must be defined in the json file.

three.js version 77

Answer №2

Encountered a problem where the color displayed wasn't the dominant color of the image, but rather the bottom left pixel. Understanding how images are mapped to textures in webgl can be beneficial in resolving this issue.

The reason for the solid color display is likely due to missing UV coordinates in the imported model. UV coordinates, also known as Texture coordinates, are essential for applying textures correctly in WebGL. Without these coordinates, the texture mapping will not work as expected.

Inspecting the JSON export from Blender may reveal an empty UV array in the UV-less version of your model. Simplifying the export by using a basic shape like a cube can help identify this issue more clearly.

To address this problem, ensure that you export your model from Blender as 'geometry' instead of 'BufferGeometry'. This option enables the 'face materials' checkbox which generates the necessary UV coordinates for texture mapping. Checking the exported JSON file should now show a populated uv array, allowing you to apply textures seamlessly.

For further insights, I recommend exploring the fundamentals of textures in WebGL on the WebGL Fundamentals page.

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

PHP query for beginners. Integrating JavaScript into a PHP webpage

Hey there! I am not familiar with PHP development, as I have never worked with it before. However, I have been tasked with adding a Google Shopping cart tracking code to a website. After someone completes an order, they are sent to finishorder.php. Upon re ...

Tips for accessing the final index of an array by looping through it and decrementing it in the following iteration

Currently, I am working on sending information by looping over an array that is nested within another array using the broadcast function. My challenge is to broadcast the message in reverse order without actually reversing the array I am iterating throug ...

Issue with Setting Value in JQuery Select Box

I am in the process of designing a webpage that allows users to edit listings they have created on my website. These listings fall under three main categories, each with its own set of subcategories. To streamline this process, I am implementing AJAX to dy ...

To begin, formulating a blank state entity containing a collection of key-value pairs with JSON objects as the values. Subsequently, modifying the contents of

I am working on setting up a reactJS state with an empty array to start. When I receive a message in the form of a JSON object, I want to add a key-value pair to the array, using the received message as the value and a specified key. For example: We have ...

The marker on the Three JS globe is constantly visible inside the globe or positioned far outside its boundaries

As a beginner in programming and React three fiber, I am struggling to understand why the marker I place on the globe using geolocation data won't stay attached. Despite my attempts to convert latitude and longitude to Cartesian coordinates, the marke ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...

encoding the special character "ü" in json_encode as either 'ü' or '&#

I've developed a function that extracts the title from a given URL and returns it in JSON format. The function is invoked by an AJAX call. Everything works smoothly, but when a title contains characters like ü or any related ones, it returns null. Wh ...

Gather input from a form and store it in an Object upon submission

I am facing a challenge as I do not have much experience with object-oriented JavaScript. My goal is to have a form submit details such as the first and last name to an object that I've created. Here is the object I have: function Person(firstName, ...

Discover the best way to transfer hook values to CreateContext in React

In my project, I've implemented a component called SideBarBlurChange. Within this component, there is a requirement to pass a value named values inside the BlurChangeValue array, which is nested within the CreateContext. I have searched online for ex ...

Tips for resizing a two-dimensional circle using a small graphical user interface in THREE.js

My goal is to adjust the size of a circle by dragging a small GUI slider. I've developed this code which creates a circular shape with a blue outline on a black background using an orthographic camera: setUpGUI(); let radius = 0.6; let ver ...

A React component created in a class cannot effectively update its state when using a functional component to pass

I'm currently working on a React project that involves both a Class component and a Functional Component. In my Class component, I have a function that updates the name in its state. The issue arises when I try to pass this function as a property to t ...

Issue with handling click events on action column in Datatable using jQuery

Utilizing jquery datatable with an action column containing "edit" and "delete" links. The table populates correctly, but encountering an issue when trying to open a bootstrap modal form upon clicking the edit button within the table. However, the modal do ...

How to pause a loop temporarily before proceeding with the next iteration

I am facing a challenge where I want to trigger two events simultaneously, but only one event should be allowed to continue at a time. If an event is already in progress, I need the ability to forcefully stop it and allow the other event to take control. S ...

The jquery click event is not working as expected

Hey there, I've been working on creating a dropdown menu that can be activated by clicking for better usability on touch screens. $('a.dropsmall2').click(function() { $(this).next('ul').slideToggle(500,'easeInOutQuad'); ...

Is it possible to use a variable in JSX within a map function to modify inline CSS styles?

I have a map function that loops through an array and generates divs on the DOM for each color item. The array consists of hex values representing different colors (e.g. #1a703f). The goal is to set the background of each div to match the corresponding co ...

Hiding javascript code within comment tags "<!-- //-->"

Years ago, I started a practice of enclosing all my JavaScript code in files with <!-- Code goes here //--> I'm not entirely sure why I did this. Maybe it was to hide the code from old browsers, is that right? Do I still need to do this? I ...

Issue with background image resizing when touched on mobile Chrome due to background-size property set to cover

My current challenge involves setting a background image for a mobile page using a new image specifically designed for mobile devices. The image is set with the property background-size: cover, and it works perfectly on all platforms except for mobile Chro ...

Top Strategies for PHP - Managing Directs and Header Content

PHP is a versatile language frequently used for generating 'templates' like headers to maintain a consistent look across websites and simplify updates via require or include commands. Another common task involves managing log-ins and redirecting ...

The conversion of a newline in an Angular page is done using &lt;br/&gt tag

Here is a function I have: setLocalVariableOnAccepted(ogp, hb, responseJson) { if (responseJson.ofgp === undefined) { this.ogpStatus = 'orange'; this.ogpStatusMsg = responseJson.ofgp + ', <br/> No change. Previous va ...

What is the best way to retrieve JSON values based on a key using JavaScript, jQuery, or AngularJS?

Here is some JSON data that I need help with: var jsonData = { "title": "Testing", "settings": { "mySettings": false }, "jsonList": ["TestingList"], "testJsonVals": { "Test1": { "name": "name1", ...