Experience the ability to dynamically alter an image in a 360-degree

<div style="margin-bottom: 200px">  
    <a href="#" onclick="cambio()"> sdsadasdas</a>
</div>

<div id="container"></div>
<div id="info"> </div>

When I click on a button, I want to change the image dynamically in an HTML element using three.js.

<!-- <script src="three.min.js"></script> -->
<script>
    var camera, scene, renderer;

    var texture_placeholder,
    isUserInteracting = false,
    onMouseDownMouseX = 0, onMouseDownMouseY = 0,
    lon = 0, onMouseDownLon = 0,
    lat = 0, onMouseDownLat = 0,
    phi = 0, theta = 0;

    var imagen='HabitacionPrincipal'
    init(imagen);

    function cambio(){
    //Any code that needs to be inserted here to dynamically change the image?

    }

    function init(imagen) {
        var container, mesh;
        container = document.getElementById( 'container' );
        camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1100 );
        camera.target = new THREE.Vector3( 0, 0, 0 );
        scene = new THREE.Scene();

        var geometry = new THREE.SphereGeometry( 500, 60, 40 );
        geometry.applyMatrix( new THREE.Matrix4().makeScale( -1, 1, 1 ) );

        console.log(imagen)
            var material = new THREE.MeshBasicMaterial( {
                map: THREE.ImageUtils.loadTexture( imagen+'.jpg' )
            } );

        mesh = new THREE.Mesh( geometry, material );    
        scene.add( mesh );

        renderer = new THREE.WebGLRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );
        container.appendChild( renderer.domElement );

        window.addEventListener( 'resize', onWindowResize, false ); 
        animate();
    }
</script>

To update the image with a different one, I need to select it beforehand.

I encountered some challenges while attempting this and received help from the following post:

Threejs Change image at runtime

Answer №1

To ensure the variable is accessible globally, expand its scope beyond just the init() function.

Imagine it like a puzzle piece in a larger picture - place material outside of both init() and cambio() so that it can be accessed by both functions. Begin by declaring it at the beginning:

var camera, scene, renderer, material;

Then, within the init() function, initialize material without using var:

function init(image) {
    // ...

    material = new THREE.MeshBasicMaterial( {
        map: THREE.ImageUtils.loadTexture(image+'.jpg')
    } );

    // ...
}

When you are ready to execute cambio(), the material will be globally accessible. This allows you to modify its properties, such as changing its map:

function cambio() {
    material.map = THREE.ImageUtils.loadTexture('secondImage.jpg');
}

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

Why does the API in Next Js get triggered multiple times instead of just once, even when the strict mode is set to false?

React Query Issue I am currently facing an issue with React Query where the API is being triggered multiple times instead of just once when the selectedAmc value changes. I have tried setting strict mode to false in next.config.js, but that didn't so ...

Safari compatible JavaScript needed for enforcing required fields in HTML5

I have been using the following script to adjust the HTML5 required attribute of my input elements. However, I am now looking for a way to tweak this script so that it can also function properly in Safari browsers, where support for this attribute may be l ...

Issue with AdminLite 2.4.0 data table functionality malfunctioning

Check out this template that I'm using. I've copied all the contents for the bower_components and dist folders, and made sure to link and require everything properly. There are no 404 errors, only status code 200. Here is a snippet of my code: ...

Stable header that jumps to the top when scrolled

I have implemented the JavaScript code below to set the header to a fixed position when it reaches the top of the page so that it remains visible while the user scrolls. Everything appears to be functional, but the header movement is abrupt and not smooth. ...

Having issues transferring the variable from JavaScript to PHP?

When attempting to pass a variable via AJAX request in JavaScript, I am encountering an issue where the variable is not being received in my PHP file. I'm unsure of where the problem lies. Can anyone help? JavaScript code var build = { m_count : ...

Tips for verifying the status of an input element following the dynamic addition of a required element

I have implemented a required field for all input elements in a specific state using the following code: for (var i = 0; i < data.length; i++) { // activate required function v = data[i].Required; if (v) document.ge ...

Implement a jQuery click event on a dynamically generated button in the code-behind

A button (Replybtn) is dynamically created when clicked in the code-behind file. --Default.aspx.cs-- protected void ReloadThePanelDetails_Click(object sender, EventArgs e) { litResultDetails.Text = litResultDetails.Text + "<button id='Replyb ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

Is there a way to verify that all images have been successfully loaded following an

Is it possible to determine when all images have finished loading from an appended HTML source in order to trigger another function? $(document).ready(function () { $('a.load-more').click(function (e) { e.preventDefault(); $.ajax({ ...

How to retrieve the value instead of the key/ID in a Laravel controller?

I am extracting data from the database and displaying it on the invoice view page using the json_encode($items); function. When I try to insert the 'price' field into the database, only the id/key is being stored instead of the actual value. Any ...

Using bluebird library for revoking promises

Recently, I've been diving into the bluebird promises library. To practice using it, I set up a basic express app with just one file and one route - a GET request to /test. The scenario I'm working on involves a promise with an interval that res ...

Using React Native to Store Items in Flatlist via AsyncStorage

My challenge involves displaying/storing a list of items in a flatlist. The issue arises when I save an item and then load it on another screen; there seems to be a repetitive pattern (refer to the screenshot). Additionally, adding a new item results in re ...

Mirror the input text to another input within a for loop

I have a list of questions displayed, each with an input field for entering a phone number. How can I use jQuery or JavaScript in a for-loop to mirror the text entered in the first phone input box to all subsequent phone input boxes? ..Enter your phone... ...

Tips for avoiding node js from exposing .git directories and its contents

I understand that by using a .htaccess file, I can restrict files from being served under .git. However, I am unsure of how to achieve the same functionality when using a node.js server. I typically use forever to start and stop the servers. Below is the ...

Encountering issues while retrieving information from database through AJAX and PHP

Update: The initial section of this question has been resolved and is now updated with the working code. ~ I'm currently developing a JavaScript application, and I'm encountering challenges with making an AJAX call function properly. While I ha ...

Python responding to an Ajax request using jQuery

Currently, I am experimenting with integrating a pre-built inline editor from the following source: https://github.com/wbotelhos/inplace Regrettably, the available support documentation is lacking and my expertise in Javascript, jQuery, or Ajax is limited ...

Begin counting when a particular div element is visible on the screen

I have a plugins.init.js file that contains a try-catch block which runs on page load. I am looking for a way to execute this code only once when the div with the class counter-value comes into view. Is there a method to achieve this? try { const count ...

Error encountered when using the enter or return key with directive syntax

Newbie Alert I'm encountering something strange while attempting to create a custom directive in AngularJS. When I input this code: myModule.directive('myTab', function(){ console.log('--Inside TAB directive--'); return ...

Is it possible to retrieve a specific property from an object in JSON format using Javascript?

As a beginner in JavaScript, I've been diving into the world of objects and trying to grasp how they function. var data = JSON.stringify({name: "Y", age: 1990}); console.log(data); // → {"name":"Y","age":1990} Out of sheer curiosity, I decided to ...

Scrolling through a list while the user types in the search bar

I am currently working on a table that populates based on an array of country objects, and I have added a search bar to enable live filtering through the countries array. However, as a newcomer to Vue, I am struggling to implement this feature effectively. ...