What is the process for altering the background using buttons in three.js?

As a newcomer to three.js, I'm looking for guidance on how to change the background by clicking a button. It seems like using "switch" and "break" might not be the right approach in this scenario. Would utilizing .loadTexture be a better alternative?

<html lang="en">
    <head>
        <title>gyroscopic</title>
        <meta charset="utf-8">
        <meta name="viewport" content="user-scalable=no, initial-scale=1">
        <style>
            body {
                margin: 0px;
                background-color: #000000;
                overflow: hidden;
            }
        </style>
    </head>
    <body>

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

        <script src="three.min.js"></script>
        <script src="DeviceOrientationControls.js"></script>

        <script>
            (function() {
                  "use strict"

                  window.addEventListener('load', function() {

                        var container, camera, scene, renderer, controls, geometry, mesh;

                        var animate = function(){

                            window.requestAnimationFrame( animate );

                            controls.update();
                            renderer.render(scene, camera);

                        };

                        container = document.getElementById( 'container' );

                        camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 1100);

                        controls = new THREE.DeviceOrientationControls( camera );

                        scene = new THREE.Scene();

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

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

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

                        var geometry = new THREE.BoxGeometry( 100, 100, 100, 4, 4, 4 );
                        var mesh = new THREE.Mesh( geometry, material );
                        scene.add( mesh );

                        renderer = new THREE.WebGLRenderer();
                        renderer.setSize(window.innerWidth, window.innerHeight);
                        renderer.domElement.style.position = 'absolute';
                        renderer.domElement.style.top = 0;
                        container.appendChild(renderer.domElement);

                        window.addEventListener('resize', function() {

                            camera.aspect = window.innerWidth / window.innerHeight;
                            camera.updateProjectionMatrix();
                            renderer.setSize( window.innerWidth, window.innerHeight );

                        }, false);

                        animate();

                  }, false);

            })();
        </script>

    </body>
</html>

Answer №1

To change the texture of an object, you can use the .loadTexture method within a button click listener.

Here's how you could implement this in your HTML:

<button id="change-texture">Change Texture</button>

Then in your JavaScript:

var textureButton = document.getElementById('change-texture');

textureButton.addEventListener('click', function(){
   material.map = THREE.ImageUtils.loadTexture('//new texture path//');
});

Remember to update the //new texture path// with the URL of your new texture image.

It should automatically update the material on the mesh as well, but it would be best to test it out to confirm.

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

Top method for displaying loading popup using $http

As a newcomer to Angular, I am curious to know if it's possible to achieve the following scenario and also where I can find documentation to help me get started. The scenario: In my MEAN app, there is currently a 'loading...' popup controll ...

Tips for displaying text within an input field labeled "password" and then reverting back to a password display after entering text

I am working with a login form that includes a password field: <input type="password" name="password" id="password" value="Password" maxlength="40" required style="width: 130px; font-size: 10px;" /> Currently, the password field displays "******** ...

Tips for effectively utilizing typescript interface with the OR operator

I'm a beginner when it comes to TypeScript. I have the following code snippet that I am working on: interface InitialData { active: boolean; status: boolean; } interface Item { id: number; name: string; Data: InitialData; } interface Main ...

Enabling specific special characters for validation in Angular applications

How can we create a regex pattern that allows letters, numbers, and certain special characters (- and .) while disallowing others? #Code private _createModelForm(): FormGroup { return this.formBuilder.group({ propertyId: this.data.propertyId, ...

Will the cloning of server components React elements negate their performance advantages?

Recently, I decided to explore React Server Components within NextJS 13, and I encountered a situation where I needed to implement the practice of passing server components as props to a client component. Specifically, I needed to utilize a higher-order co ...

Error: Uncaught TypeError when using a for loop in Vue and GraphQL

I encountered a TypeError while attempting to iterate through a GraphQL query in my Vue project. The script snippet in question is as follows: <script> import { useQuery } from "@vue/apollo-composable"; import gql from "graphql-tag&qu ...

Is an XMLHttpRequest necessary for updating a JSON file value using JavaScript?

Currently, I am working on a game feature that allows users to change their display name and then save it in a JSON file for easy access across different files and pages. I initially included an XMLHttpRequest in my code, but after stumbling upon this insi ...

Node.js seems to be having trouble with emitting events and catching them

I'm having trouble troubleshooting my code. // emitter.js var EventEmitter = require('events').EventEmitter; var util = require('util'); function Loadfun(param1, param2, db){ function __error(error, row){ if(error){ ...

Poor placement of wireframehelper in Three.js group

I have an assembly object that contains a PlaneBufferGeometry and a wireframehelper. Both are added to the group. The planebufferGeometry is initially positioned at 0,0,0. After using the following code: group.setposition(100,100,0) I noticed that the p ...

I need to confirm the validity of minDate and maxDate in a ReactJS component, ensuring that maxDate is always at least 5 years after min

start from today and select a date end 5 years from the starting date I haven't attempted anything yet. Seeking help for a solution. ...

Utilizing jQuery AJAX to transfer files from the client side in .NET platform

I need to upload files from the client side using a jQuery Ajax function to a location on a different server, rather than sending them to my application's web server. This is to prevent unauthorized or virus-infected uploads to the application web ser ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

Add a directive on the fly, establish a connection, and display it dynamically

Within my markup, I have a tag element called popup-window which is handled by a specific directive. If I wish to incorporate multiple similar widgets that can be displayed or hidden in various locations, I currently need to include all these elements dire ...

Attempting to invoke a function containing a promise in Javascript

Calling the function numberOfRedeems(dealId) from another function named setUpData raises an issue where the numberOfRedeems() function, which includes a promise and returns "counter", always returns as undefined when executed within the setUpData function ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Conditionality in the ng-repeat directive of AngularJS

Could someone please help with setting a condition in ng-repeat inside a custom directive call? <map-marker ng-repeat='obj in objects' title= 'obj.name' latitude= 'obj.last_point().latitude' longitude= ' ...

Is there a way to rotate label text on a radar chart using chart js?

I am working with a Chart js radar diagram that contains 24 labels. My goal is to rotate each label text by 15 degrees clockwise from the previous one: starting with 'Label 1' at the top in a vertical position, then rotating 'Label 2' ...

The Bootstrap 5 navigation bar does not extend to the full width of its parent

While working on a Bootstrap navigation inside a container, I encountered an issue where the navigation bar was not expanding to match the width of the container. It seemed like the padding had to be manually adjusted to fit properly. Below is the code sn ...

Struggling to update the color of my SpeedDial component in MUI

I'm having trouble changing the color of my speed dial button. The makeStyle function has been working fine for everything else. Any suggestions? import React, {useContext} from 'react'; import {AppBar, Box, Button, Container, makeStyles, To ...

Define a universal URL within JavaScript for use across the program

When working with an ASP.NET MVC application, we often find ourselves calling web service and web API methods from JavaScript files. However, a common issue that arises is the need to update the url in multiple .js files whenever it changes. Is there a me ...