Loading material textures in Three.JS using data URLs - A simple guide

I am currently working with three.js and have successfully combined a mesh (.obj), a material (.mtl), and several textures into a single JSON object.

The mesh and material were exported from Blender's wavefront obj export feature.

Below is a snippet of the JSON file:

{
    "data": {
        "type": "b64obj",
        "material": "--Long base64-encoded Material data--",
        "mesh": "--Long base64-encoded Mesh data--",
        "textures": {
            "texture.jpg": "base64-encoded image",
            "anothertexture.jpg": "base64-encoded image",
        }
    }
}

Outlined below is the code snippet that loads this JSON object (excluding the base64-decoding part):

var mtlLoader = new THREE.MTLLoader();
var materials = mtlLoader.parse(data.material);
materials.preload();

var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
var object = objLoader.parse(data.mesh);
renderObj(object); //begin using it within the application once loaded

The .mtl file references image files that are expected to be on the hard drive. How can I instruct the system to use the object containing the textures instead?

Answer №1

Prepare yourself, as things are about to get a bit messy. You'll have to make some adjustments to MTLLoader by intercepting requests for specific URLs and substituting them with Data URIs.

var json = JSON.parse(myJSON);

var _loadTexture = THREE.MTLLoader.MaterialCreator.prototype.loadTexture;

THREE.MTLLoader.MaterialCreator.prototype.loadTexture = function ( url, mapping, onLoad, onProgress, onError ) {

  url = json.data.textures[ url ] || url;
  return _loadTexture( url, mapping, onLoad, onProgress, onError );

};

I've suggested a less convoluted method for achieving this — I implemented it for drag-and-drop functionality — but I'm unsure if it will gain enough traction to be officially adopted.

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

Tips on how to retrieve a variable from an array in Vue JS

New to Javascript and Vue, I am exploring examples to grasp the fundamental concepts. <template> /*<p v-bind:class="['bold', 'italic', isValid ? 'valid' : 'invalid']">*/ <p v-bind:class= ...

How to extract nested array from an object using JavaScript and Express

Upon examination of the object below: [ { id: 5fc0be2990a8a12cc0ba0b5c, projectName: 'E-271120-B', projectManagaer: '5f7f1ba973ff621da4322248', dataInici: 2020-11-26T23:00:00.000Z, dataEntrega: 2020-11-26T23:00:00. ...

Setting the initial state with an undo action in React: a step-by-step guide

Is it possible to display a snackbar with an undo action when dragging and dropping events in a react-big-calendar? https://i.stack.imgur.com/QFmYA.png I am trying to implement functionality where clicking on the undo action will revert the event back to ...

Implementing 3D model loading with Three.js

Recently, I've delved into learning Three.js and hit a roadblock while trying to load gltf files. Despite fixing all errors in my code, the model refuses to show up on my webpage. Here's the snippet causing the issue: function init() { ...

Toggling with Jquery when an image is clicked

I'm trying to wrap my head around the functionality of jquery toggle. My goal is to toggle to the next anchor element with the class plr-anchor when an image with the class go_down is clicked. The information is being populated using maps. Javascript ...

Encountering the error message "The function $(...).tablesorter is not defined" while using webpack

After updating to Rails 6 with Webpack, I'm encountering the error message Uncaught TypeError: $(...).tablesorter is not a function. Below is the snippet of my environment.js file: const { environment } = require('@rails/webpacker') const w ...

Is it possible to dynamically adjust texture UV mapping?

My geometry is a rectangle with dimensions W x H and a texture that is 2*W x H. I only want to display half of it: ... var pageGeometry = new THREE.PlaneGeometry(pageWidth, pageHeight, 1, 1); var texture = someTexture; pageGeometry ...

Issue with executing Mongoose's .save() method

I am facing an issue with a piece of code that is not functioning as expected. My goal is to save a user document after modifying it with an ObjectId by adding it to an array. However, the user.save() function does not seem to execute, as the document rema ...

Attempting to retrieve JSON data using jQuery

Currently, I have a PHP file that outputs JSON data like the following: {"news":[{"title":"title news example1","content":"blabla bla 1","img":"url"}, {"title":"title news example2","content":"blabla bla 2","img":"url2"}, {"title":"title news example3","c ...

What is the method to deactivate all events in React components using refs?

Currently, I am utilizing TreeView from Material-ui along with a text field for searching other items on the screen. Although TreeView and TextField are unrelated components. However, I have encountered an issue where if I click on a TreeView node and the ...

What sets apart "config" from "defaults" in Sencha Touch?

As a newcomer to Sencha Touch, I have one simple question that's been on my mind... Can someone explain the distinction between "config" and "defaults" in Sencha Touch? ...

Issue with clicking and toggling classes in Javascript

I am experimenting with creating a simple 3 slide slider, but I am facing some issues with the JavaScript. My goal is to have the current slider slide out and the selected one slide in when clicking on the slider color. I'm attempting to achieve this ...

Sending both data and images concurrently through AJAX JSON in ASP.NET MVC involves several steps. You can achieve this by properly

Initially, my task was to create a form with data only for sending it to the action, without including any image. However, I am now facing a new requirement to send both data and an image via POST request to the action. It seems challenging as I am unsure ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

What is the best way to create a cube in Three.js with the 4 corner points of the base and a specified height?

Given a JSON with base coordinates, I am looking to generate a cube in Three.js. The height of the cube will be a constant value, such as 1. { "points": [ { "x": 0, ...

Tips on expanding the background beyond the boundaries of a parent container with a specific width limit

Could you please take a look at the code snippet below? I am dealing with a situation where I have a container with a fixed width, and inside that container, there are rows whose width exceeds that of the parent container. Some of these rows have a backgro ...

Using Spring Portlet to send an Ajax post request to the Controller with Jquery

EDIT: The start and end dates are stored as joda DateTime in the POJO and I am encountering the following error: SystemOut O 14:10:16.040 [WebContainer : 2] DEBUG org.springframework.beans.BeanUtils - No property editor [org.joda.time.DateTimeEditor] ...

JSON data cannot be transmitted using AJAX

I created a function that tracks the time spent on a specific page and where the user came from. The data is collected and saved into a JSON object, but I encountered an issue when trying to send this JSON via ajax. Upon successful sending, I receive an em ...

What could be the reason my mat-form-field is not displaying the label?

I'm currently working on a project using Angular Material to build a web page. I am facing an issue with the mat-form-field component as the label is not displaying, and I can't figure out why. Any assistance would be greatly appreciated. Thank y ...

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...