eliminate a mesh from the view following a mouse hover event triggered by a raycaster

           

When loading a gltf model, I want to make sure that a mesh is only displayed when the object is hovered over. I have successfully managed to change its material color using

INTERSECTED.material.color.setHex(radioHoverColor);
and reset it once the mouse leaves the object.
However, I am struggling to figure out how to remove the mesh once the mouse moves away from the object.
The mesh just remains in the scene.
I tried adding scene.remove(radioOutline.mesh), but it does not work outside the if statement. If I move all the radioOutline code outside the if statement, it throws an error stating that intersects[0] is undefined, which is understandable.

I have provided an example hosted on GitHub with GitHub Pages integration.

       var radioMaterial = new THREE.MeshBasicMaterial({color: 0x0fffAA, side: THREE.BackSide});
        class outlineMesh {
            constructor(geometry) {
                this.mesh = new THREE.Mesh(geometry, radioMaterial);
            }
        }
        
        // https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Mouse-Over.html
        // Mouse hover event -> raycaster 
        function onHover(event) {
            event.preventDefault();
            raycaster.setFromCamera( mouse, camera );
            var intersects = raycaster.intersectObject( radioModel );
 
            if ( intersects.length > 0 ) {
 
                let radioOutline = new outlineMesh(intersects[0].object.geometry);
                radioOutline.mesh.position.set(1.4,-0.5,1.2);
                radioOutline.mesh.rotation.y = -0.3;
                radioOutline.mesh.scale.multiplyScalar(1.6);
                scene.add(radioOutline.mesh);
 
                if ( intersects[0].object != INTERSECTED ) {
                    if ( INTERSECTED ) {
                        INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
                    }
                    INTERSECTED = intersects[0].object;
                    INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
                    INTERSECTED.material.color.setHex(radioHoverColor);
                    cursor.style.cursor = "pointer";
                }
            } else {
                if ( INTERSECTED ) {
                    INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
                }
                INTERSECTED = null;
                cursor.style.cursor = "default";
            }
        }
   

Answer №1

To eliminate the mesh from the current scene, all you need to do is:

scene.remove(mesh);

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

Execute a simulated click function in JavaScript without causing the viewport to move

I have successfully implemented a sticky add to cart feature on my Shopify store. However, there seems to be an issue where clicking on the variations in the sticky area also triggers the same variations on the product page, making it difficult for users t ...

What is the correct way to generate an await expression by utilizing recast/esprima?

I have an issue with a JavaScript function export const cleanUp = async () => { await User.destroy({ where: {} }); }; I am attempting to add a line below await User.destroy({ where: {} }) using recast.parse(`await ${module}.destroy({ where: {} } ...

Issue with by.cssContainingText function not performing as intended

I have a container that I want to be able to click on. Here's how it looks: <div class="CG-Item CG-B-Left ng-binding" ng-bind="SPL.showTitleText">My New SPL</div> So I am trying to use this code to click on it: element(by.cssContainingT ...

Leveraging Vue 3 Composition API with accessors

I'm currently in the process of refactoring some of my components using the composition API. One component is giving me trouble, specifically with asynchronous state when trying to retrieve data from one of its getters. Initially, the component was u ...

Using Single Quotes as Parameters in JavaScript

I'm currently facing an issue with a function that is designed to populate a field in the parent window when clicked. Specifically, it is meant to fill in a text field with a name. The challenge I am encountering arises when the field contains a sing ...

Exploring the Power of Laravel 5.5 and Vue.js 2.x for Efficient API Calls

Currently, I am working on a Laravel 5.5 project locally that incorporates Vue.js 2.5.9 with XAMP Server. One of the tasks I have is to load certain information onto the DOM and then refresh it upon clicking the "Refresh" button. However, there seems to ...

When looking at react/17.0.1/umd/react.development.js, it becomes evident that ReactDOM is not defined

I'm currently immersing myself in learning React with the help of React Quickly, written by Azat Mardan, which is based on React v15.5.4. The examples provided in the book typically include two essential files: react.js and react-dom.js, such as in th ...

Tips for resolving the error message "TypeError: Converting circular structure to JSON"

I had a straightforward query where I needed to select all from the aliases table. Everything was working fine until I ran npm update. TypeError: Converting circular structure to JSON public async fetchAliases(req: Request, res: Response): Promise< ...

How to display text on a new line using HTML and CSS?

How can I properly display formatted text in HTML with a text string from my database? The text should be contained within a <div class="col-xs-12"> and nested inside the div, there should be a <pre> tag. When the text size exceeds the width o ...

Issues with loading times and the rendering of textures in ThreeJS

Having imported a 3D chair object from Blender into ThreeJS, I am encountering some issues. Firstly, the load time is over 40 seconds, which seems excessively long and may be related to Visual Studio. Additionally, the textures of the image are not loadi ...

Is it possible for my node.js to become unresponsive when comparing lists?

In my node.js app, I have two lists - one retrieved from a database and the other created by listing file names on a server. Both lists contain approximately 750,000 strings each, and now I need to search for each string in one list within the other. As a ...

Newbie mishap: Utilizing an array retrieved from a function in javascript/jquery

After submitting the form, I call a function called getPosts and pass a variable str through it. My aim is to retrieve the data returned from the function. // Triggered upon form submission $('form#getSome').submit(function(){ var str = $("f ...

Time for the browser to evaluate javascript code has arrived

We are looking to enhance the speed at which our Javascript files load in the browser. Although our own Javascript files are simple and small, larger libraries like jQuery and KendoUI take a considerable amount of time to evaluate. We are interested in fin ...

Retrieve the element located within a "block" element that is relative to the user's click event, without the

I'm pondering whether it's feasible, but here's my concept: Within my page, there are multiple identical blocks with the same classes, differing only in content. I am unable or unwilling to assign IDs because these blocks are dynamically g ...

Combining JS and PHP for secure function escaping

Looking for a solution to properly escape quotes in generated PHP Javascript code. Here is an example of the current output: foreach ($array as $element) { echo '<a onClick="myFunctionTakesPHPValues('.$element[0].','.$element[1] ...

Ways to modify CombinedCamera attributes within Three.JS?

After experimenting with the Near Clipping Plane parameter and updating the camera, I made an interesting discovery. I initially created a camera with a near clipping plane set to 10, but then attempted to change it to 700. However, despite my code adjust ...

Retrieving a subset of JSON data from a larger JSON object in a Node.js environment

I'm working with a JSON object structured like this: [ { "id": "458712e247328e4ebfafeb4d922b", "value": [ 1 ], "location": null, "metadata": null, "at": "2015-07-16T16:33:39.113Z" }, { "id": "1ghj78d8220734c00ab941 ...

When requesting a Node.js API from Javascript fetch, the session custom property is throwing an undefined error

I am currently working on a User Login Project, where the APIs are built using Node.js and Express. The UI part is developed using HTML and JavaScript, with these components existing as separate projects. Upon user login, a fetch call is made in JavaScrip ...

Does the arrangement of props matter in JSX?

Assuming the o object has a key/value pair of: foo: 'bar', can I expect these results to hold true?: // foo will be 'bar' <MyComponent foo='should not override' {...o} /> // foo will be 'overridden' ...

Altering the state ahead of rendering

I am experiencing an issue where the Parent component is passing empty props to the Child component. This may be due to my attempt to set the state of my data within a function instead of in a constructor (for the Parent component). I only want the state o ...