Enhancing your scene with new objects using three.js

Exploring the possibilities with three.js, I am working with two shapes: "squares" and a "sphere".

Each shape has an associated button. When the user clicks a button, the corresponding shape is added to the scene. However, there can only be one square and one sphere in the scene at a time.

The issue I'm facing is that when a new square is added, it should replace the existing one. Unfortunately, my current code doesn't seem to achieve this as the previous square remains when adding a new one.

Any suggestions or advice on how to solve this problem would be greatly appreciated. Thank you!

<html>
  <head>
    <title>My second three.js app</title>
    <style>
      body { margin: 0; }
      canvas { width: 100%; height: 100% }
    </style>
  </head>
  <body>
    <button id="button1">Square1</button>
    <button id="button2">Square2</button>
    <button id="button3">Sphere</button>
    <script src="js/three.js"></script>
    <script>
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

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

  loader.load( 'square1.glb', function ( geometry ) {

    geometry.scene.traverse( function ( node ) {

        if ( node.isMesh ){
            square = node;
            square.material.map.anisotropy = maxAnisotropy;
        }

    document.getElementById("button1").addEventListener("click", function(){
      scene.remove(square);
      scene.add(square);

    });

  });

  loader.load( 'square2.glb', function ( geometry ) {

    geometry.scene.traverse( function ( node ) {

      if ( node.isMesh ){
          square = node;
          square.material.map.anisotropy = maxAnisotropy;
      }

    document.getElementById("button2").addEventListener("click", function(){
      scene.remove(square);
      scene.add(square);

    });

  });

  loader.load( 'sphere.glb', function ( geometry ) {

    geometry.scene.traverse( function ( node ) {

      if ( node.isMesh ){
          sphere = node;
          sphere.material.map.anisotropy = maxAnisotropy;
      }

    document.getElementById("button3").addEventListener("click", function(){

    scene.add(sphere);

    });

  });

  var animate = function () {
    requestAnimationFrame( animate );
    renderer.render( scene, camera );
  };

  animate();
</script>
  </body>
</html>

Answer №1

It is important to keep track of the "current square" shape outside of your <button> click handlers to ensure that adding and removing these shapes from the scene works correctly.

Instead of calling scene.remove() on the shape object you want to add, make sure to remove the current square shape (if it exists) before adding a new one:

/* Updated code snippet */
document.getElementById("button1").addEventListener("click", function(){

  if(currentSquare) {
    scene.remove(currentSquare); /* Remove the current square shape */
  }

  scene.add(square); /* Add the new square shape to the scene */
});

You can modify your script as shown below:

// Your three.js initialization code goes here

var currentSquare = '';
var currentSphere = '';

// Define a function to load different shapes
function loadShape(filename, onLoaded) {

  // Loading logic goes here

}

// Load the first square shape
loadShape('square1.glb', function(nextSquare) {

    document.getElementById("button1").addEventListener("click", function(){

        if(currentSquare) {
            scene.remove(currentSquare);
        }

        scene.add(nextSquare);  
        currentSquare = nextSquare;
    });
})

// Load other shapes using the same approach

var animate = function () {
  requestAnimationFrame( animate );
  renderer.render( scene, camera );
};

animate();

By following this approach, you should have better control over adding and removing shapes in your three.js scene. Hope this guidance helps!

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

Guide to implementing the onchange event in JavaScript for this specific scenario

How can the onchange event be utilized in this scenario using JavaScript? First, input data into the input with id="one". Subsequently, the data in the input with id="two" will be updated to match the data in the input with id="one". However, when the da ...

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

I am encountering an issue where I am unable to successfully fetch a cookie from the Express backend to the React

const express = require("express"); // const storiesRouter = require("./routes/storiesRouter") // const postsRouter = require("./routes/postsRouter"); // const usersRouter = require("./routes/usersRouter"); const cors = require("cors"); const cookieParser ...

What causes ngClick to stop working following $compile?

http://plnkr.co/edit/kL2uLPQu2vHHKIvRuLPp?p=preview Upon button click, the controller calls a service to compile HTML and inject it into the body. The compiled HTML (displaying "Hello World" from $scope.name) is referring to the scope of the controller, ...

Adding various textures onto a SphereGeometry in three.js

In my three.js project, I am experimenting with creating a sphere using both a base material and a transparent png material layered on top. While researching how to achieve this effect, I came across a helpful answer that demonstrated loading multiple mate ...

Overwriting private functions in JavaScript

I am currently implementing a workaround for some of jQuery's Draggable code. My objective is to make changes without altering the original source files and dynamically patch one of the internal functions. The specific function _generatePosition is ...

Erroneous deletion issue in React list causing removal of incorrect item

While working on creating a todo list in React, I faced an issue when trying to implement a delete function. The problem arose when attempting to delete an item - instead of removing the selected item, React ended up deleting everything except that specif ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

Completing a submission on a bootstrap form, using innerHTML and displaying an alert

I am currently having an issue with navigating to the home page after submitting a form in Bootstrap. Although I have successfully implemented an alert message upon submission, the page does not redirect to the home page as expected. Instead, it redirects ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

The functionality of the Javascript window.print() method is limited to a single use

I've been working on an Angular project and I have the following code snippet implemented in one of the components. Everything works fine when I try to print for the first time using the onClickPrint() method, but it doesn't seem to trigger when ...

Keying objects based on the values of an array

Given the array: const arr = ['foo', 'bar', 'bax']; I am looking to create an object using the array entries: const obj = { foo: true, bar: true, bax: false, fax: true, // TypeScript should display an error here becau ...

Click event triggers dynamic function call

Is it possible to have different functions for ng-click depending on the loaded controller page? <a ng-click="removeEvent(event)" class="top_menu_link"> REMOVE</a> For instance, if I want the same button to trigger a remove action but on diff ...

AngularJs Resource provides the functionality to pass optional parameters through the URL

Currently, I am utilizing this type of resource: var Products = $resource('companies/:companyId/products') However, the issue arises when I attempt to access the products from all companies via the URL companies/products. Instead of receiving the ...

Handling unauthorized responses in Vue.js using axios interceptor

When checking my console, I noticed the following error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'message') at eval. Below is a snippet from my axios.js file: axiosIns.interceptors.response.use( response =& ...

Implementing lazy loading functionality with jQuery for an image grid within an AngularJS single page application

Recently, I decided to enhance my GUI for boom by incorporating Lazy Loading of images. This GUI is constructed using AngularJS. I have a working version that loads all images, which I have shared through this Gist link: https://gist.github.com/brock/67241 ...

How can we identify if a React component is stateless/functional?

Two types of components exist in my React project: functional/stateless and those inherited from React.Component: const Component1 = () => (<span>Hello</span>) class Component2 extends React.Component { render() { return (<span> ...

Exploring the Angular Checkbox n-Change - is it really all about 'this'?

Looking for a solution with a series of checkboxes: <input type="checkbox" ng-change="??????"> I am trying to figure out how to set $scope.mode.someOtherValue = false when the checkbox is checked. Any ideas on how to extract the checkbox value wi ...

Express.js and gridfs-stream are unable to retrieve the error

Imagine an effortless image download server where Express.js takes the request, fetches an image from MongoDB GridFS, and serves it as a response. Everything works fine when the request is valid and the file exists. The issue arises when it fails to catc ...

Web performance issues noticed with Angular 8 and Webpack 3.7 rendering speed

My web application is currently taking 35 seconds to render or at least 1.15 seconds from the initial Webpack start. I've made efforts to optimize Webpack, which has improved the launch speed, but the majority of time is consumed after loading main.j ...