Erasing object THREE that has already been sketched

Currently, I am attempting to create a code for observing splines. The issue I am encountering is related to the menu functionality - when I select a new spline option, the previously drawn spline remains visible on the screen despite my efforts to remove it from the scene.

<html>
  <head>
    <title> Exploring Spline Visualizations </title>
      <style>
        body { margin: 0; }
        canvas { width: 100%; height: 100% }
      </style>
  </head>
  <body>
    <script src="js/three.js"></script>
    <script src="js/TrackballControls.js"></script>
    <script>
      var camera, cameraControls,scene,renderer,dropdown,container,info;
      var numPoints = 100;

      sampleSpline = new THREE.CatmullRomCurve3([
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(0, 200, 0),
        new THREE.Vector3(150, 150, 0),
        new THREE.Vector3(150, 50, 0),
        new THREE.Vector3(250, 100, 0),
        new THREE.Vector3(250, 300, 0)
      ]);

      sampleSpline2 = new THREE.CatmullRomCurve3([
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(0, -200, 0),
        new THREE.Vector3(-150, -150, 0),
        new THREE.Vector3(-150, -50, 0),
        new THREE.Vector3(-250, -100, 0),
        new THREE.Vector3(-250, -300, 0)
      ]);

      sampleSpline.type='catmullrom';
      sampleSpline2.type='catmullrom';

      var splines ={
        sampleSpline: sampleSpline,
        sampleSpline2: sampleSpline2
      };

      var dropdown = '<select id="dropdown" onchange="addSpline(this.value)">';
      var s;
      for ( s in splines ) {
        dropdown += '<option value="' + s + '"';
        dropdown += '>' + s + '</option>';
      }
      dropdown += '</select>';

      function addSpline(){

        var value = document.getElementById('dropdown').value;
        var selectspline = splines[value];

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

        var material = new THREE.LineBasicMaterial({
          color: 0xff00f0,
        });

        var geometry = new THREE.Geometry();
        var splinePoints = selectspline.getPoints(numPoints);

        for(var i = 0; i < splinePoints.length; i++)
        {
          geometry.vertices.push(splinePoints[i]);  
        }

        var line = new THREE.Line(geometry, material);
        scene.add(line);

      }

      init();
      animate();

      function init()
      {
        container = document.createElement('div');
        document.body.appendChild(container);

        info = document.createElement('div');
        info.style.position = 'absolute';
        info.style.top = '10px';
        info.style.width = '100%';
        info.style.textAlign = 'center';
        info.innerHTML = dropdown;
        container.appendChild(info);

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

        camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,10000);
        camera.position.z= 700;

        cameraControls = new THREE.TrackballControls(camera,renderer.domElement)

        cameraControls.rotateSpeed = 5.0;
        cameraControls.zoomSpeed = 1.0;

        cameraControls.noZoom = false;
        cameraControls.noPan = true;

        cameraControls.staticMoving = true;
        cameraControls.dynamicDampingFactor = 0.3;

        cameraControls.addEventListener('change',render);

        scene = new THREE.Scene();

        camera.lookAt(scene.position);

        addSpline();

        renderer.setClearColor(0xdddddd, 1);

        window.addEventListener( 'resize', onWindowResize, false );

        render();
      }

      function onWindowResize() 
      {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
        cameraControls.handleResize();
        render();
      }


      function animate() 
      {
        requestAnimationFrame( animate );
        cameraControls.update();
      }
      function render()
      {
        renderer.render( scene, camera );
      }

    </script>
  </body>
</html>

Answer №1

the variable line is local to the addSpline function,

try this code snippet:

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

When you keep line inside the function, it will always be considered as undefined. Moving the line variable declaration outside of the function and into other global variables is a solution.

var camera, cameraControls, scene, renderer, dropdown, container,info,
line;

Simply remove the var declaration from within the function:

var

line = new THREE.Line(geometry, material);

It's also recommended to properly dispose of the material and avoid overusing global variables, but addressing these issues is beyond the scope of this question.

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

Can Selenium in JavaScript be used to retrieve child elements from a webpage?

I've been struggling to adapt my JavaScript script for use with Selenium (also in JavaScript). Despite numerous attempts, I haven't been able to find a solution. I've attached an image to better explain my question await chromeDriver.findEle ...

Why does AngularJS treat $http response.data as an object, even though PHP sends back a JSON string?

I am struggling with an AJAX call to PHP. The Angular code seems simple: $http( { // ... } ) .then( function cf_handle_success( response ) { console.log( response.data ) ; // --> [object Object] } , ...

"Error encountered while trying to perform a JavaScript _doPostBack

In my asp.net application, I have an HTML table where each td element has a unique id. When a td element is clicked, I use JavaScript to store the id in a hidden field. After that, I attempt to trigger _doPostBack from JavaScript to utilize the hidden fiel ...

Is the top bar feature malfunctioning in version 4.3.2 of Foundation?

During my previous project, I utilized the open-source Foundation 4 framework and successfully implemented a top bar navigation. Now, as I embark on a new project with Foundation, I have downloaded the Foundation 4.3.2 version from . Despite referencing th ...

Applying the active state to the link will cause it to inherit the default styles of the

I am facing a challenge with overriding the active style of links in a universal manner, to restore them to their original state when they cannot be interacted with (such as during scrolling). In my current code, I implemented this: .scrolling a:active { ...

It seems that the `to` required prop was missing in the `Link` component of React-Router

Currently, I am facing an issue while trying to integrate react-router. The error message I'm encountering is: Failed propType: Required prop to was not specified in Link. Check the render method of app. Unfortunately, I am unable to pinpoint ex ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

Link together a series of AJAX requests with intervals and share data between them

I am currently developing a method to execute a series of 3 ajax calls for each variable in an array of data with a delay between each call. After referring to this response, I am attempting to modify the code to achieve the following: Introduce a del ...

Adjusting the size of a Vue component on the fly

I'm struggling to find a way to dynamically adjust the width of a component. The component I am working with is called 'vue-burger-menu' -> https://github.com/mbj36/vue-burger-menu. To set the width, you need to assign a number to the p ...

Optimizing Divs for Maximum Layout Efficiency

My current issue involves a series of divs that contain varying amounts of content. These divs are floated left and I am striving to align them seamlessly without any vertical space between them (except for the 10px margin that I have included). You can v ...

EJS files do not show variables passed from Node

I am currently developing a 'preferences' section on my website, where users can make changes to their email addresses and passwords. Within this preferences page, I aim to showcase the user's current email address. router.get("/settings", ...

When I switch to mobile view, my navigation menu vanishes

Currently in the process of creating a website using WordPress, specifically with a divi theme and utilizing a windows operating system. It seems that everything appears correctly on desktop, however when resizing the window or viewing the site on a mobile ...

Implementing a dual hover effect on a Div element

I am working with HTML code that includes an image and text <div class="subcontainer1"> <img src="a.png" alt="" class="imgcolumn"> <h3 class="header3">Hello</h3> </div> This setup places the content above the image. ...

Include a selection of images within a popover box

I am currently working on a component that contains various experiences, each with its own popover. My goal is to display an array of images within each popover. Specifically, I have different arrays of images named gastronomiaExperience, deportesExperien ...

Concluding the use of angular-bootstrap-datetimepicker when selecting a date

I am currently utilizing the UI Bootstrap drop-down component to display the angular-bootstrap-datetimepicker calendar upon clicking. Although it works well for the most part, I have encountered an issue where the calendar block does not close when clicked ...

How can I implement a scroll bar in Angular?

I am facing an issue with my dialog box where the expansion panel on the left side of the column is causing Item 3 to go missing or appear underneath the left column when I expand the last header. I am looking for a solution to add a scroll bar so that it ...

Struggling to make changes to a Styled Component in a React application

In a certain file, I have a BaseComponent composed of various other components and being exported. The top level of the BaseComponent contains a wrapper responsible for managing margins. When I export it and attempt to override some styles with: //other fi ...

Using JavaScript and AJAX to manage and control a shell interface

Looking to create an HTML page that includes a YouTube video and utilizes JavaScript with the YouTube API. The objective is to embed a video and test if it has been fully downloaded using the YouTube API. I have set up an Apache server with MySQL and PHP ...

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

Adjust the href link value when a new option is selected

I currently have a select element displayed below. Next to it, there is a link that sets the eID value to a session value. However, I want this value to be updated dynamically whenever a different eID value is selected from the dropdown. Although I can r ...