Interacting with mouse events on every <g> element within an SVG file integrated into the three.js material

I am currently loading SVG images onto the mesh basic material of a BoxBufferGeometry(cube) using SVGLoader. My goal is to trigger mouse events when a user hovers or clicks on a specific element of the SVG which is loaded on a particular side of the cube.

I attempted to add events directly into the .svg file before loading it, but once it is placed on the material, no changes caused by the events are visible.

Is there an alternative method to select the elements of a loaded svg image and apply events to them?

For better comprehension, please take a look at http://plnkr.co/edit/YYN8aechHGTKXvPv6tOo?p=preview. I've also tried accessing a particular side using the following code:

raycaster.setFromCamera( mouse, camera );

var intersects = raycaster.intersectObjects( scene.children );
if ( intersects.length > 0 ) {
    var index = Math.floor( intersects[0].faceIndex / 2 );
    if ( INTERSECTED != intersects[ 0 ].object && (index == 4 || index == 5)) {
        if ( INTERSECTED ) {
            INTERSECTED.material[intersects[0].faceIndex].color.setHex( INTERSECTED.currentHex );
        }

        INTERSECTED = intersects[ 0 ].object;
        INTERSECTED.currentHex = INTERSECTED.material[4].color.getHex();
        INTERSECTED.material[index].color.setHex( 0xCACACA );
        f = index;
}

Answer №1

Utilizing threex.domevent.js, I managed to capture the mouseover event and put together a plunker. My main goal was to identify the cube face containing the SVG image. Explore more at: detect mouse click / hover event on sides of cube in three js and https://github.com/jeromeetienne/threex.domevents.

  • Implement the dom event using *threex.domevent.js**

    domEvents  = new THREEx.DomEvents(camera, renderer.domElement)

  • Observe the mouse over event to pinpoint the desired face.

            domEvents.addEventListener(mesh, 'mouseover', function(event) {
            var vector = new THREE.Vector3(
                (event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, );
            vector.unproject(camera);
            raycaster.set(camera.position, vector.sub(camera.position).normalize());
    
            var intersects = raycaster.intersectObject(mesh);
            if (intersects.length > 0) {
                var index = Math.floor(intersects[0].faceIndex / 2);
                if (index === 4) {
                    //index 4 represents the cube face with the svg image,
                    //you can load a new svg or perform desired actions here
                    console.log('##############');
                    mesh.material[4].map = new THREE.TextureLoader().load('sample2.svg');
                }
    
            }
        }, false)
    

    Access Plunker for demonstration: http://plnkr.co/edit/QXwqN3X70ex3EZmlKhRf?p=preview Hope this proves helpful.

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

Tips for updating and transferring a variable within a callback function

I have implemented a function using the SoundCloud API that retrieves a song URL, obtains the associated sound ID from the API, and then passes that ID to a callback for streaming purposes and updating the page. The data is successfully retrieved from the ...

What is the process for removing a property from the prototype within an array of MongoDB objects?

I have a database in MongoDB/Mongoose where I store user information, including passwords. However, when I want to display a list of contacts on the frontend, I don't want to include the passwords for security reasons. To achieve this, I attempted to ...

The website on iPad automatically zooms in upon opening and then increases the zoom level even further when a specific button is tapped

I recently coded a website using html, css, and js. It seems to work perfectly on all devices except for the iPad. Interestingly, when I use the iPad emulator in Google Chrome, everything appears normal. However, when I open the website on an actual iPad, ...

Set iframe or form to be in a fixed position

Having issues with my site where an iframe is contained within a div. When only one character is entered in the telephone box, validation fails and red warning text is displayed. Furthermore, after clicking in the email box and pressing tab twice, the fo ...

Encountered an issue when attempting to establish a connection with the REST

I am encountering an issue with connecting to a web service deployed on an Apache server using Jersey. The error message I receive is: Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' ...

Encountering a syntax error while utilizing a JavaScript variable in a jQuery selector for a lightbox feature

I'm currently working on creating a lightbox feature and have reached the stage where I am implementing next and previous buttons to navigate through images. I am utilizing console.log to check if the correct href is being retrieved when the next butt ...

Locate the exact cursor position upon user click and showcase a div at the same spot

I am seeking a solution to determine the exact position of the cursor where a user has clicked. My goal is to display a div at the bottom side of the page wherever the user clicks. For instance, on the Stack Overflow homepage, if someone clicks on the lo ...

Unable to utilize await within a then statement to make a subsequent API call in a React application

Here is my scenario: I am making a call to one API, and in the `then` section of that API call, I am making another API call. The output of the first API will be passed as input to the second API. await axios .post(process.env + '/certificates/uplo ...

How can I align the selected option to the left in a CSS/jQuery selectbox?

I've been struggling to get the selected option aligned left like the other dropdown options. Even though I've added 'text-align:left;' in every CSS option, it's not working. I suspect that the JavaScript code is affecting the al ...

The dynamic functionality of the Bootstrap React Modal Component seems to be malfunctioning

I'm encountering an issue with React Bootstrap. I'm using the map function in JavaScript to iterate through admins. While all values outside the modal display correctly from the admins array, inside the modal only one standard object from the arr ...

What is the best way to include an Observable in this function?

Every time I send a set of credentials to my API and receive the data that needs to be stored, I encounter an error during the login process. Error: TypeError: You have provided an invalid object when a stream was expected. You can provide an Observable ...

What is the process for incorporating an image from your local system into jsfiddle?

<img src="file://C:/Users/User/Desktop/food-Wallpaper.png" height="200" width="600"/> <div id="heading"> EXPLORE The top-rated Eateries </div> <div> <select id="location"> ...

"Transforming Selections in Illustrator through Scripting: A Step-by-Step Guide

In Illustrator, I successfully used an ExtendScript Toolkit JavaScript code to select multiple elements like text, paths, and symbols across different layers. Now, I am looking to resize them uniformly and then reposition them together. While I can apply ...

Encountering a blank or 404 error page in React after running npm build - let's troubleshoot where the issue might be

Upon running npm build(react), my index.html displays a blank page. To address this issue, I initially attempted the following steps: Adding the following line in package.json homepage : "./" or "." or "absolute file PATH" ...

Encountering issues when implementing Parse.Cloud.httpRequest within Express - reporting a lack of success method available

When attempting to access a Facebook graph search URL using Parse Express, I encounter an issue. The request is made using Parse.Cloud.httpRequest. Instead of a successful response, I receive a 500 Internal Server Error. Upon inspecting the logs, I find t ...

Activating gzip compression using fetch.js

I am utilizing fetch.js (https://github.com/github/fetch) to transmit a rather substantial JSON object to the backend. The size of the JSON is significant due to it containing an SVG image string. My question is whether fetch.js applies gzip compression a ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

In Internet Explorer 11, React 15.4.1 does not support using objects as valid child components

When trying to render a collection of children in React, make sure to use an array instead of objects. If you encounter the error "Objects are not valid as a React child," consider wrapping the object using createFragment(object) from the React add-ons. Do ...

A Step-by-Step Guide to Implementing Social Logins (Facebook, Google, LinkedIn, and Github) in Angular 6

https://i.sstatic.net/QLDZ6.png Configuration in App.module.ts const config = new AuthServiceConfig( [ {id:GoogleLoginProvider.PROVIDER_ID, provider:new GoogleLoginProvider('358720783918-g6gv4vsabi786qcj0sbvkm2v36totpio.apps.googleusercontent.com&ap ...

What could be the reason behind the occurrence of an error after deleting certain lines of code

The code below is functioning correctly. obj = { go: function() { alert(this) } } obj.go(); // object (obj.go)(); // object (a = obj.go)(); // window (0 || obj.go)(); // window However, an error arises when I comment out the first two lines. obj ...