Utilize A-frame image resources within JavaScript code

Currently, I am utilizing an image as a texture in multiple instances. Once through the material component and another time within a custom component where I am using THREE.TextureLoader(), resulting in the application loading the image two times. I believe there might be a more efficient approach.

Present Scenario

HTML

<!-- Assets -->
<a-assets>
  <img id="my-map" src="path/to/map.jpg">
  <a-asset-item id="my-model" src=path/to/model.gltf""></a-asset-item>
</a-assets>

<!-- Entities -->
<a-box material="src: #my-map">
<a-entity gltf-model="src: #my-model" custom-component="mymap: #my-map">

JS

// custom-component extract
schema: { mymap: { type: 'map' } }
init: function() 
{
    let mesh = this.el.getObject3D('mesh')
    mesh.traverse( function( child ) 
    {
        if ( child.isMesh )
        {   
            let TextureLoader = new THREE.TextureLoader()
            let mymap = TextureLoader.load( data.mymap )

            child.material = new THREE.MeshPhongMaterial({ map: mymap })
            child.material.needsUpdate = true;
        }
    })
}

Query

Is there a way to use the same image asset in the custom component without redundantly loading it?

Answer №1

Your code currently utilizes mesh.traverse(), which iterates through each child of the mesh object and calls a function. This may result in TextureLoader.load() being called multiple times if there are more than one child within your mesh. To prevent this, it is recommended to remove the load call from within the traverse() method. By making this adjustment, the image should only be loaded once.

let mesh = this.el.getObject3D('mesh')
let TextureLoader = new THREE.TextureLoader()
let mymap = TextureLoader.load( data.mymap )

mesh.traverse( function( child ) 
{
    if ( child.isMesh )
    {   
        child.material = new THREE.MeshPhongMaterial({ map: mymap })
        child.material.needsUpdate = true;
    }
})

Answer №2

After conducting research within the ThreeJs codebase, I have discovered that the TextureLoader relies on the ImageLoader, which checks if an image has already been loaded in the THREE.Cache before loading a new one.

When images are loaded as img in AFrame, they are not stored in the THREE.Cache, resulting in the image being loaded twice. However, loading the image as a-asset-item does store it in the cache.

Therefore, there is no need to make changes to the JavaScript code. Simply use a-asset-item instead of img.

For further information, refer to the AFrame documentation

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

Is it possible to trigger an AJAX function from a popup using the "Colorbox - a jQuery lightbox plugin"?

Currently, my website utilizes PHP, Smarty, jQuery, and the Colorbox jQuery plugin. All necessary files have been included in the index.tpl file, ensuring smooth functionality without any issues. Within a Smarty template file, I have implemented a Colorbo ...

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

Having difficulty showcasing the JSON data within the dropdown list within an HTML table

In my HTML table, I have 4 rows with Order ID and Product Comments columns disabled. Users can enter data in other columns and submit it. Upon submission, I receive a JSON object which I iterate through and display in the table. I am facing two challenges ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

Tips for combining Meshes and Textures seamlessly

I am faced with a situation where I have multiple meshes, each with its own unique texture. My goal is to combine these meshes into one: mergedGeo.merge( mesh.geometry, mesh.matrix); Surprisingly, this process works seamlessly. However, when I attempt t ...

Using Selenium: Checking for existing dropdown values and incrementing if necessary

I am currently working on automating an application using Selenium Webdriver with Java. The web application I am testing has an Add button that, when clicked, triggers the activation of a dropdown menu. Subsequent clicks on the Add button reveal additional ...

Passing events from a grandchild component up to its grandparent component in VueJS 2.0

Vue.js 2.0 appears to have a limitation where events cannot be emitted directly from a grand child component to its grand parent. Vue.component('parent', { template: '<div>I am the parent - {{ action }} <child @eventtriggered="pe ...

Encountering difficulties with implementing getStaticProps in _app.js

I'm currently working with next.js and facing a challenge with the following tasks: To fetch basic user-related data such as a title for the navbar and social links for the footer in _app.js. To pass this data down to other components like Foote ...

Can a variable be initialized with a concealed or additional argument?

After just 2 weeks of coding, I'm struggling to find information on how to initialize a variable with an extra argument in a recursive function call. Is this even possible? And if it is, are there any scenarios where it's considered best practice ...

jQuery encounters a 400 error while attempting to make a GET request

I have been using a jQuery ajax GET request that sends a clientId to the server. If the clientId is invalid, the server returns a 400 "Bad token etc..." error message. While this setup works fine, I am puzzled by why jQuery displays this error in the conso ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

Trouble with executing asynchronous AJAX request using when() and then() functions

Here is the code that I am currently using: function accessControl(userId) { return $.ajax({ url: "userwidgets", type: "get", dataType: 'json', data: { userid: userId } }); }; var user ...

What could be causing errors with my addrole command in discord.jsV12?

After updating to discord.jsv13, my addrole command is no longer working properly. I keep getting errors like role.id is not a function or role.id is not defined, even though I can't seem to find any errors in my code. I have experience with JavaScrip ...

Extend JavaScript capabilities for window.print() function to automatically include backgrounds

I am looking to add a special magical property to my Print this Page button. This property will automatically enable the default unset option (shown in the picture) which is to print the backgrounds of div colors and background images. <a href="#" oncl ...

"Enhance your webpage with a captivating opaque background image using Bootstrap

I'm new to exploring Bootstrap and I am currently experimenting with options for displaying content with a semi-transparent background image. Currently, I am using a "well" but I am open to other suggestions. I have managed to place the image inside t ...

Steps for embedding a custom function in a switch statement

I am attempting to run a switch statement based on the argument provided to the function below. I have been trying to call different functions depending on the argument passed. However, I encountered an Uncaught ReferenceError in the beginning of the .js f ...

Dynamic font size that adjusts as you change the window dimensions

Is there a way to adjust the font size in HTML so that when I resize the window, the text size adjusts accordingly? It's like setting a percentage for the text based on the size of the container it is in. Let me provide an example of what I have in m ...

Javascript timeout clearing problem

One thing I'm curious about is whether or not clearTimeout() halts the timer and prevents the function within the timer from being executed, or if it simply clears the timeout and runs the function immediately. Take a look at this example: $('i ...

Express application failed to deploy due to boot timeout error R10

After researching extensively on Stack Overflow and various other websites, I have been unable to solve a problem with my small Express app using ES6 syntax. Upon deploying it to Heroku, I encountered the following error: LOGS : 2021-04-09T12:14:14.688546 ...

Utilize alternating colors from the Material UI palette to enhance the appearance of

Can someone help me understand how to utilize the different color variants in Material UI? For instance, the theme primary color has various options like 100, 200, 300, 400, 500, and so on. How can I access these colors from within my component? I attempt ...