Using Preloaded Images as Textures in THREE.js: A Step-by-Step Guide

This specific project includes a fallback routine for non-canvas, using a preloading method for images. Although the images are added and loaded correctly, I am facing an issue with integrating them into THREE.js as it tends to reload the images using its own image loader.

** Check out the JavaScript code below **

function MAIN_PRELOAD() {

 var Preload_List = [];
 var Preload_Loaded = 0;
 var Preload_Errors = 0;

 function preload_scene() {

  // Ignore if List is Empty...
  if(SceneAssets.length < 1) return;
  for(var i in SceneAssets) {

   // Skip if Blank...
   if(SceneAssets[i]['material']['map'].length < 1) continue;

   // Skip Repeats...
   if(Preload_List.indexOf(SceneAssets[i]['material']['map']) >= 0) continue;

   // Add to list...
   console.log('Image added to preloader: '+SceneAssets[i]['material']['map']);
   Preload_List[Preload_List.length] = SceneAssets[i]['material']['map'];

  }
 }

 function preload_masks() {

  // Ignore if List is Empty...
  if(MaskLayer['textures'].length < 1) return;
  for(var i in MaskLayer['textures']) {

   // Skip if Blank...
   if(MaskLayer['textures'][i].length < 1) continue;

   // Skip Repeats...
   if(Preload_List.indexOf(MaskLayer['textures'][i]) >= 0) continue;

   // Add to list...
   console.log('Image added to preloader: '+MaskLayer['textures'][i]);
   Preload_List[Preload_List.length] = MaskLayer['textures'][i];

  }
 }

 function preload_finished() {

  console.log('Preloading has finished!');
  // NYI: Hide the loading overlay...
  init();
  animate();

 }

 function preload_init() {

  // Preload Assets...
  preload_scene();
  preload_masks();

  // Finish if empty...
  if(Preload_List.length < 1) {
   preload_finished();
   return;
  }

  // Iterate if filled...
  for(var i in Preload_List) {

   // Enclosure for event trapping...
   (function(i) {

    var imageElement = document.createElement('img');

    imageElement.onload = function() {
     console.log('Image "'+Preload_List[i]+'" done loading!');
     Preload_Loaded ++;
     if(Preload_Loaded + Preload_Errors == Preload_List.length) {
      preload_finished();
     }
    };

    imageElement.onerror = function() {
     console.log('Image "'+Preload_List[i]+'" failed to load...');
     Preload_Errors ++;
     if(Preload_Loaded + Preload_Errors == Preload_List.length) {
      preload_finished();
     }
    };

    imageElement.src = Preload_List[i];

   })(i);

  }

 }
 preload_init();

}

MAIN_PRELOAD();

Currently, there is no solid overlay implemented yet, that masks everything until the presentation preload is complete.

Just to clarify, each part of my application functions well independently. However, there is a noticeable stutter at the start when everything loads and gets added to the scene, impacting the user experience negatively.

Additionally, there are intermittent stutters during the presentation when loading masking layers as required, resulting in new HTTP requests instead of utilizing the browser cache via THREE.ImageUtils.loadTexture().

I believe I need to somehow replace the THREE.ImageUtils.loadTexture() with the un-appended img element created in the preloader to optimize caching of scene assets for THREE.js, but I haven't found any examples of this technique being used elsewhere. It could potentially enhance performance if successfully implemented.

Any alternative solutions to address this issue would also be appreciated.

Using THREE.js r70

Answer №1

let texture;
const imageElement = document.createElement('img');
imageElement.onload = function(event) {
    texture = new THREE.Texture( this );
    texture.needsUpdate = true;
    initialize();
};
imageElement.src = "myimage.png";

function initialize() {
    material = new THREE.MeshPhongMaterial( { map : texture } );
}

Check out this example on JSFiddle.
DISCLAIMER: In the provided fiddle, I am using an image dataUrl to avoid CORS issues. In a real website, you would typically set the image src to a regular file path.

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 are some alternative methods for downloading the latest file version without relying on the client cache?

On my webpage, I have a table displaying users' data. Each row represents a user and includes their business card, which is a clickable tag that opens a PDF file stored on the server. <td class="business_card"> <a href="/static/users_doc ...

JavaScript is incapable of locating image files

I am encountering Resource Not Found errors for the image files I am attempting to load into var manifest. Despite following the tutorial code closely, I can't seem to identify what is causing this issue... (function () { "use strict"; WinJS.Bin ...

Require a click for activation post adding the element

Check out the code snippet below: HTML: <p>Click this paragraph.</p> JS: $("p").on("click", function(){ alert("The paragraph was clicked."); $("body").append("<p>This was newly added. This also has a click event.</p>" ...

CASL user update has been refreshed

My CASL implementation is quite basic and I've noticed that the documentation lacks detail. The code I'm using is essentially a copy-paste from the docs: import { abilitiesPlugin } from '@casl/vue' import defineAbilitiesFor from &apos ...

Error received when attempting AJAX call with jQuery 1.7.2: NS_ERROR_XPC_NOT_ENOUGH_ARGS

Encountering an issue with jQuery version 1.7.2 and the ajax function. When running the code snippet below, Firefox Firebug console displays the following error: NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace] var wei ...

Spin Picture while Moving Down

I'm currently working on a website where I want the arrow images to rotate when a contact form is expanded, and then rotate back when it's collapsed. Here's the code I've been using: $(document).ready(function(){ $ ...

I would like to store my json object in a text file so that my JavaScript code can access and read it from there. The goal is to efficiently utilize the file system for data retrieval within

Can someone please assist me with storing my JSON object in a text file and then reading it from that file using JavaScript? I am unsure about how to do this. Any help is appreciated. var objects = [{ "Object": { "ID": 1, &q ...

What is the process for setting up a new router?

When it comes to templates, the vuestic-admin template from https://github.com/epicmaxco/vuestic-admin stands out as the perfect fit for my needs. However, I have a specific requirement to customize it by adding a new page without displaying it in the side ...

Having trouble entering text into a textarea field labeled with "area-label" and receiving an error stating that the element

Apologies for the vague title, can someone suggest a better one? Here are the details of the issue I am encountering: Website: https://www.desmos.com/calculator/lzidy3m70r Steps: Click on the + button on the top left Select images and upload an image U ...

Why is the "class" attribute of an SVG node not being applied when I change it?

I am having trouble changing the "class" attribute of a node in SVG using my AngularJS Directive. Even though I've written the code to do so, it doesn't seem to be applied properly. This is the code snippet from my Directive: node = node.data(f ...

Block public access to the root directory of my domain to enhance security

I have a website at www.domain.com. While inspecting the element and trying to access www.domain.com/css/, I noticed that it displayed all the files in the directory. The structure is as follows: /css/ /images/ /include/ /js/ index.html contact.html si ...

The MongoClient.connect method fails to return a valid response

I am currently working with a node.js file that looks like this: var express = require('express'); var app = express(); var mongoClient = require('mongodb').MongoClient; app.get('/',(req, res)=>{ console.log(connect ...

The left and right arrows maintain their visibility even when they are outside of the image

I am a beginner in the world of web development and I am trying to implement left and right navigation for images using arrows. My goal is to have the arrows fade in when the mouse hovers over the image and fade out when it's moved away. However, I am ...

Changing the date in an EditText field on Android Studio

Can someone assist me in updating an EditText with the selected date from a DatePicker as it changes? Here is my code: private View view; private Button next; private EditText birthday; private DatePicker datePicker; @Override public ...

Controlling worldwide modules using Node Version Manager

Currently, I am utilizing nvm as a tool to manage node.js / io.js versions, encountering difficulties with global modules every time I update node. Recently, I attempted to install npm i express-generator -g. I noticed an older version in /usr/local/bin a ...

How can jQuery Validate show validation messages specific to each field?

I need to validate numerous mandatory fields and display alert messages in a specific format: "Please fill in" followed by the field label. Currently, I am manually implementing this validation method as shown below: $("#myform").validate({ rules: { ...

When I scroll and update my webpage, the navigation header tends to lose its distinct features. This issue can be resolved

When I scroll, my navigation header changes from being transparent to having a solid color, and this feature works perfectly. However, whenever I refresh the page while already halfway down, the properties of my navigation header are reset and it reverts ...

Having issues updating cookies with jQuery in ASP.NET framework

On my asp.net web page, I have implemented a search filter functionality using cookies. The filter consists of a checkbox list populated with various categories such as sports, music, and food. Using a jQuery onchange event, I capture the index and categor ...

Is it considered inefficient to import every single one of my web components using separate <script> tags?

Currently, I am in the process of developing a website with Express + EJS where server-side rendering is crucial. To achieve this, I am utilizing web components without shadow dom. Each page type (home, post, page) has its own EJS view. For instance, when ...

Interactable elements on a spherical map in three.js

I've been trying to implement raycasting to make objects clickable. Despite referencing numerous examples, the code doesn't seem to work for me. The only notable difference is that I'm working within a sphere. My initial setup involves defi ...