Modifying vertices in THREE.LineSegment: Adding and deleting

I am facing an issue with a THREE.LineSegments object, where I need to dynamically change the number of vertices. However, when I try to modify the geometry vertices array, the lines with removed vertices remain in place.

Is there a way to remove vertices from the geometry after it has been created?

For example, I have a LineSegments object with 3 segments, and I want to later change it to have only 2 segments. The last line segment persists even after the change.

var scene,
                renderer,
                camera;

            var line;

            initScene();
            initLine();

            setInterval(update, 500);

            function initScene() {

                camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000),
                    scene = new THREE.Scene();
                renderer = new THREE.WebGLRenderer();

                camera.position.z = 5;
                scene.add(camera);

                renderer.setSize(window.innerWidth, window.innerHeight);
                document.body.appendChild(renderer.domElement);

            }

            function initLine() {

                var verts = [
                    randomV3(),
                    randomV3(),
                    randomV3(),
                    randomV3()
                ];

                var geom = new THREE.Geometry();

                geom.vertices = [
                    verts[0], verts[1],
                    verts[1], verts[2],
                    verts[2], verts[3]
                ];

                line = new THREE.LineSegments(geom, new THREE.LineBasicMaterial({
                    color: 0xff00ff,
                    linewidth: 3
                }));

                scene.add(line);
                renderer.render(scene, camera);

            }

            function update() {

                var verts = [
                    randomV3(),
                    randomV3(),
                    randomV3()
                ];

                line.geometry.vertices = [
                    verts[0], verts[1],
                    verts[1], verts[2]
                ];
                line.geometry.verticesNeedUpdate = true;

                renderer.render(scene, camera);

            }

            function randomV3() {
                return new THREE.Vector3(
                    (Math.random() * 4) - 2,
                    (Math.random() * 4) - 2,
                    0
                )
            }
            
body {
                margin: 0;
                padding: 0;
            }
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/103/three.min.js"></script>

Answer №1

If you're looking for a solution to this issue, one method is to first dispose of the old geometry and then create a new one like this:

line.geometry.dispose();

line.geometry = new THREE.Geometry();

line.geometry.vertices = [
  verts[0], verts[1],
  verts[1], verts[2]
];

You can see this approach in action in this fiddle. However, it's recommended to consider using THREE.BufferGeometry for a more future-proof solution since THREE.Geometry may not be renderable in the future. Here's the same code in a fiddle with THREE.BufferGeometry.

Another option is to create a THREE.BufferGeometry with enough buffer space to accommodate the largest line object in your application. This is important because you can't resize buffers, only update their contents. You can find more details in this guide:

By the way, note that setting linewidth won't affect the width of line primitives in three.js. They will always have a width of 1 pixel.

three.js R103

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

Convert the contents of the uploaded file to a JSON format

I've recently started using angularjs for file uploads and came across this helpful model on github: https://github.com/danialfarid/angular-file-upload The file upload process is working smoothly for me. However, I'm facing a challenge after upl ...

When utilizing AJAX XMLHttpRequest, the concatenated response text from Symfony's StreamedResponse becomes apparent

Below is the code for a controller that returns Line 1 as soon as the endpoint is called and then two seconds later it returns Line 2. When accessing the URL directly at http://ajax.dev/app_dev.php/v2, everything works as expected. /** * @Method({"GET"}) ...

What is the most efficient way to add an attribute in jQuery - using the attr() method, passing attributes as a key-value object, or directly?

There are three ways that I am aware of for adding a href attribute with a relative link in jQuery: using (1) .attr(), (2) attributes as key-value pair in an argument, or (3) direct writing (if you know other methods, please share in your response so I can ...

Ways to Achieve the Following with JavaScript, Cascading Style Sheets, and Hypertext

Can someone help me convert this image into HTML/CSS code? I'm completely lost on how to do this and don't even know where to start searching for answers. Any assistance would be greatly appreciated. Thank you in advance. ...

Unable to connect to the cloud firestore backend specifically on the deployed version

When deploying the project using Vercel, I included my Firebase security and project details as environment variables on the Vercel dashboard. Authentication works fine during deployment, but there is an error in the console: @firebase/firestore: Firesto ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

Tips for enhancing the presentation of JSON information

I recently ventured into the world of JSON and JS, managing to create a JSON file to showcase data using .onclick event. While I have successfully generated and displayed the JSON data on screen, my next goal is to present it in a table format for better c ...

In the setup function, the composition API calculates the return value of the computed property before it is

I am currently working on editing a post using the state manager Vuex in Vue3 with Composition API. Below is the code I have implemented: <template> <div class="container py-5"> <h3 class="mb-5 border-top-0 border-start- ...

What is the method for implementing an Inset FAB with Material UI in a React project?

Currently, I am working on a project that requires an "Inset Fab" button to be placed between containers. After referencing the Material Design documentation, I discovered that the component is officially named "Inset FAB". While I was able to find some tu ...

Can the execution of a jQuery Timeout function be halted if a user navigates away from the page?

Implementing a timer in a view with jQuery: var timer, myDiv = $('#mydiv'); $(document).on('mousemove', function(ev) { var _self = $(ev.target); clearTimeout(timer); if (_self.attr('id') === 'mydiv' || ...

I have a question about CSS selectors: How can I change the font color of a parent <li> element when the child

After struggling for hours, I'm finally throwing in the towel on this issue. I have an unordered list with no background at the top level and text color of #fff. When rolled over, the background turns #fff and the text color turns #000. The child ul ...

Replicating form fields using jQuery

I have come across many questions similar to mine, but unfortunately none of them address the specific details I am looking for. On a single page, I have multiple forms all structured in the same way: <form> <div class="form-group"> ...

Can a form be submitted using an Ajax request triggered by a div element instead of an input type submit?

I used to submit the form by triggering $(".btn-update.").click() before, but now that I'm using $(".btn-update").ajaxForm(), the form is not getting submitted. Here is the HTML code: <form id="company-profile-edit-form" name="company-profile-edi ...

Node's getRandomValues() function is throwing an "expected Uint8Array" error

Currently, I am experimenting with the getRandomValues() function to enhance an encryption REST API that I am developing for practice. My server is using Node, which means I do not have access to a window object containing the crypto object normally housin ...

Guide to making two text boxes with SimpleDialog in jQuery Mobile

I came across the link below, but unfortunately it's not working for me. jQuery Mobile SimpleDialog with two Inputs? Is there anyone who can assist me after reviewing the code snippet provided below? <script type="text/javascript> ...

JavaScript innerHTML not functioning properly when receiving a response from a servlet

Can someone help me troubleshoot the code below? I'm receiving a response from the servlet, but I can't seem to display it inside the div. Here is the response: lukas requests to be your friend &nbsp <button value="lukas"onclick="accfr(th ...

Calculate the total price from a combination of HTML and JavaScript options without altering the values

I'm currently facing an issue in my form where the final price needs to be updated when a different option is selected. I've searched extensively for the problem without success. I've used similar code before, just with different variables a ...

Exploring the concept of self in JavaScript

Exploring the concept of "self" magic, take a peek at this excerpt from nodejs (which is not complete). Socket.prototype.connect = function(options, cb) { ...... var self = this; var pipe = !!options.path; if (this.destroyed || !this._handle) { ...

I'm puzzled by the inconsistency of my scrolltop function on mobile, as it seems to be scrolling to various parts of the page depending on my

I am encountering an issue with a function that scrolls to a specific element when a button is clicked. Strangely, this functionality works fine on desktop but fails on mobile devices. It successfully scrolls to the correct position only when at the top of ...

Guide on downloading a file from Firebase storage within a Vue-based web application

Scenario: You are in a situation where you need to download a PDF file (or any file type) from Firebase storage to your computer using a browser that has a Vue.js web app with Vuetify components. Despite having looked at the Firebase storage documentatio ...