What is the best way to remove or reset a map from a material skybox in three.js?

In my ThreeJS scene, I am trying to implement different modes for viewing all models in the skybox, with or without textures. I have two functions called 'getSkyTexture' and 'getSkyColor' which are supposed to work separately. However, when I called the 'getSkyColor' function to change the background sky color and then called the 'getSkyTexture' function to change the background sky texture, the texture did not work. As a result, I had to reset/remove the skybox map material. How can I achieve this?

function getSkyTexture(id, objMaterial){ //here objMaterial Texture image

        console.log('sky texture');

        var imagePrefix = objMaterial;
        var directions  = ["xpos","xneg","ypos","yneg","zpos","zneg"];
        var imageSuffix = ".png";

         materialArray = [];
         for (var i = 0; i < 6; i++)
         materialArray.push( new THREE.MeshBasicMaterial({
           map: THREE.ImageUtils.loadTexture( imagePrefix + directions[i] + imageSuffix ),
           side: THREE.BackSide /*depthWrite: false, fog: false*/
          }));

         var skyGeometry = new THREE.CubeGeometry( 1000, 1000, 1000);
         skyMaterial = new THREE.MeshFaceMaterial( materialArray );
         skyBox = new THREE.Mesh( skyGeometry, skyMaterial );
         scene3D.add( skyBox );

    }

    function getSkyColor(id, objMaterial){   //here objMaterial color
       
        console.log('sky color');

        var skyGeometry = new THREE.CubeGeometry( 1000, 1000,1000);
        skyMaterial = new THREE.MeshBasicMaterial({color: objMaterial, side: THREE.BackSide});
        skyBox = new THREE.Mesh( skyGeometry, skyMaterial);
        scene3D.add(skyBox);

    }

Answer №1

Here is an example demonstrating the switch of background between a color and a cube texture:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 1);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor("purple");
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var path = "https://threejs.org/examples/textures/cube/SwedishRoyalCastle/";
var format = '.jpg';
var urls = [
  path + 'px' + format, path + 'nx' + format,
  path + 'py' + format, path + 'ny' + format,
  path + 'pz' + format, path + 'nz' + format
];
var cubeTexture = new THREE.CubeTextureLoader().load(urls);

var colorTexture = new THREE.Color("purple");

var switcher = true;
btnSwitch.addEventListener("click", function() {
  scene.background = switcher === true ? cubeTexture : colorTexture;
  switcher = !switcher;
}, false);

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<button id="btnSwitch" style="position: absolute;">switch</button>

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

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Instructions on uploading a PDF file from a Wordpress page and ensuring the file is stored in the wp-content upload directory folder

What is the process for uploading a PDF file on a WordPress page? <form action="" method="POST"> <input type="file" name="file-upload" id="file-upload" /> <?php $attachment_id = media_handle_upload('file-upload', $post->I ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

Implementing Jquery to Identify the Matching Indices of Two Arrays

I need to find the indices of similar values in array1 and array2, and then save them in a variable named stored_index. array1 = ["50","51","52","53","54","55","56","57","58","59"]; array2 = ["59","55","51"]; The desired result for stored_index is: sto ...

What is the functionality of require(../) in node.js?

When encountering var foo=require(../), what specific modules does node.js search for? It may appear to look in the directory above the current one, but what exactly is it seeking and how does it function? Is there a comparison with include in C or impor ...

Ember.js - The Veggie Power-Up: [object Object] encountered an error with:

I've recently started using ember and have set up a sandbox to experiment with it. An interesting issue arises when I run the ember s command - an error pops up, but here's the strange part: the error only occurs when I have Sublime Text open (!? ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...

When Ajax attempts to run a PHP page, it redirects me to a different page

My goal is to create a live chat feature using PHP, MySQL, and AJAX. I have almost got it working perfectly, but I'm stuck on how to submit the chat message without refreshing the page. I have a PHP page called sendchat.php that takes input data and s ...

Enhancing Angular select functionality by incorporating HTML entities using ng-option

My query is somewhat linked to this specific response, although with a slight variation. What I am aiming to accomplish is the parsing of HTML entities from a string passed onto a select using ng-options. Consider the following dataset: $scope.myOptions ...

What is the best way to incorporate this HTML and script into a React component?

After receiving the embedded HTML and script from a platform, I discovered that a button triggers the script. It was originally designed to be embedded on a website, but I am attempting to integrate it into a React application. Here is the code provided fo ...

JQuery button.click() handler executes without a user click

Currently, I am in the process of tidying up the code for my auction game. However, I have encountered an issue where my function is triggered immediately after endAuction() is called rather than waiting for the button click event. Unfortunately, I am no ...

Enhancing MongoDB following a successful transaction with Stripe API

Currently, I am developing an E-Store using Express.js, MongoDB, and Stripe. This is my first project that involves handling transactions and working with databases. The structure of my project is quite unique where product information is stored in MongoD ...

Arrays crossing in the world of meteors

Currently, I am attempting to extract an array from a different collection using collection2. So far, I have managed to accomplish this with objects, as demonstrated in the example below for users: users: { type: String, label: "Inspector", option ...

What is the proper way to designate a manifest.json link tag on a limited-access website controlled by Apache shibboleth?

The issue arises when attempting to access the manifest.json file. It has been declared as follows: <link href="manifest.json" rel="manifest"/> Is it possible to declare the manifest tag inline, or what would be the most effective way to declare it ...

Tips for transferring data from the Item of a repeater to a JavaScript file through a Button click event for use in Ajax operations

I am working with a repeater that displays data from my repository: <div class="container" id="TourDetail"> <asp:Repeater ID="RptTourDetail" runat="server" DataSourceID="ODSTTitle" ItemType="Tour" EnableViewState="false" OnItemDataBound="Rp ...

Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have a ...

Having trouble getting Vue async components to function properly with Webpack's hot module replacement feature

Currently, I am attempting to asynchronously load a component. Surprisingly, it functions perfectly in the production build but encounters issues during development. During development, I utilize hot module replacement and encounter an error in the console ...

The data stored in a FormGroup does not automatically transfer to FormData

I am currently facing an issue with uploading multi-part data to my API. To achieve this, I have created a FormData object for the upload process. Initially, I gather all the necessary user input data such as an image (file) and category (string). These va ...

Getting the ID of a select input option in Vue.js using FormulateInput

Recently, I've been working with a FormulateInput select component that looks like this: <FormulateInput name="broj_zns-a" @change="setZns" :value="brojZnsa" type="select" label="Broj ZNS- ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...