Exploring ThreeJS by Casting Rays on HTML Elements

We are currently encountering an issue with ThreeJS. Our goal is to integrate HTML elements into ThreeJS and use raycasting to determine whether we are pointing to any HTML element. However, when we intersect with it, it returns an empty array. An example of this scenario can be found in the following CodePen:

https://codepen.io/wazosa/pen/OJrqRRy?editors=1111

 mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  raycaster.setFromCamera(mouse, camera);

  var intersects = raycaster.intersectObject(scene, true);
  console.log(intersects)
  if (intersects.length > 0) {
    
        var object = intersects[0].object;


  }

In this example, there is a div and a cube. Clicking on the cube will display it in the console, but clicking on the div element results in an empty array. Any suggestions on how to resolve this issue would be greatly appreciated.

Thank you in advance

Answer №1

Raycasting is a technique used to interact with objects in a three.js scene by detecting intersections. Objects that have a raycast method, like Mesh, can be targeted using a Raycaster. When you call

raycaster.intersectObject( scene, true )
, the Raycaster recursively searches through the scene for objects with the raycast method and executes it to determine if any intersections exist.

It's important to note that DIVs and other HTML elements are separate from the three.js scene as they belong to the webpage's DOM. Therefore, Raycaster cannot interact with them because it is unaware of their existence.

Exploring Options:

Option 1 suggests writing text to a texture and creating a Sprite to display the label, as Sprite supports the raycast method.

Option 2 proposes adding a representation of the HTML element to the scene, possibly using a transparent Sprite or similar billboard with correct orientation and positioning matching the 2D layout of the HTML element.

Option 3 mentions adding a click handler to an element containing labels, where the event object includes a target property representing the clicked HTML element. It also discusses the challenge of converting the 2D click position into a 3D point for spatial reference.

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

Mapping over an array and ignoring any undefined properties in a dynamic object

Looking for a way to dynamically create objects in the 'map' function to reduce the final array size. The goal is to avoid adding properties with undefined values. For example, if 'offst: undefined', skip this property but add others wi ...

Modifying the content of JSON key values

In my application, I am using MongoDB, Express, and MongoDB. When receiving data on the server side, it comes in the form of an array of objects (JSON) named upProbations. For example, let's say I find information about Max: [ { Name ...

Using JQuery to automatically scroll and anchor to the bottom of a dynamically populated div, but only if the user doesn't

I am attempting to achieve the functionality of automatically scrolling to the bottom of a div with the ID #chat-feed. The overflow for this div is set to auto, and I want it to remain at the bottom unless a user manually scrolls up. If they do scroll up, ...

Issue with karma-ng-html2js-preprocessor failing to generate modules

Struggling to configure the karma-ng-html2js-preprocessor. While Karma has been successfully detecting all my JavaScript files, it's having trouble generating a module from the HTML preprocessor. Take a look at my options object below. I've spec ...

Implementing individual NGRX Selectors for each child component to enable independent firing

My component serves as a widget on a dashboard, and I am using *ngFor to render multiple widgets based on the dashboard's data. Each WidgetComponent receives some of its data via @Input() from the parent. parent <app-widget *ngFor="let widget ...

Stopping setTimeout when leaving the current page: Is it possible?

Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the windo ...

When utilizing AJAX within a for loop, the array position may not return the correct values, even though the closure effectively binds the scope of the current value position

Is this question a duplicate of [AJAX call in for loop won't return values to correct array positions? I am following the solution by Plynx. The issue I'm facing is that the closure fails to iterate through all elements in the loop, although the ...

When attempting to use Ajax, the operation fails; however, if I directly access the URL,

When using firebug, I attempted to make the following AJAX call: var rootUrl = 'http://172.24.105.22:8080/geoserver/Chennai_Sub/ows'; var defaultParameters = { service: 'WFS', version: '1.0.0', request: 'Get ...

The callback in Jquery getJSON does not execute even when a valid JSON response is received

My server is sending valid JSON objects (as verified by jsonlint.com) that have this structure: "{\"encryption\": {\"key\": \"gKV0oPJwC5CBQxmn\"}}" This is how my HTML file looks: <html> <head> <title&g ...

Tips for sending a variable to control a particular panel within an accordion in Angular 2

I have a collection of ngbpanels that are dynamically created using ngFor. I need to expand or collapse a specific panel based on certain conditions, but the ID I provide for the panel is stored in a variable. The code does not recognize the panel ID when ...

How can you make a button in Vue only visible after all API calls have successfully retrieved the data?

Is there a way to make the report button visible only after all the data has been loaded from the latest click of the budget button? Currently, when the budget button is clicked, it retrieves budgets and displays them in a Vue grid using Kendo Grid. To spe ...

Is it possible to create a pie chart using Chart.js with data fetched through an Ajax HTTP GET

Embarking on a new journey here, this week's focus is on delving into Chartjs for canvas and brushing up on JSON usage. The task at hand includes employing an Ajax HTTP GET request to fetch the json file. However, I am currently stumped on how to trig ...

Problem with jQuery ajax: Sending an array doesn't work

I am attempting to transmit an array of data via AJAX to save it to the database. This is how I construct the array: $( "#saveordering" ).button().click(function( event ) { event.preventDefault(); var data = document.getElementByI ...

Troubleshooting problems with Chart.js scaling upon page load

Using chart.js to display a horizontal bar graph. Interestingly, upon the initial loading of the website, only a fraction of one bar is visible, and the graph fails to properly adjust to the display size until the window is manually resized. This issue per ...

Extracting information from a JSON file using React.js

I have a JSON file named data.json in my React.js project: [{"id": 1,"title": "Child Bride"}, {"id": 2, "title": "Last Time I Committed Suicide, The"}, {"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, {"id": 4, ...

Tips on how to prevent certain classes from being impacted by a hue-rotate filter applied to all elements on a webpage

I am currently in the process of adding a feature that allows users to choose between a dark or light theme, as well as select a specific theme color for the app. The implementation involves using CSS filters such as invert(1) for the dark theme and hue-ro ...

Exploring the Three JS Perspective Camera's Field of View and Distance Range

We have a model loaded on Three JS Fiber and notice that other projects with similar models have a more steady camera view, giving the illusion of the object being larger. However, our camera settings seem to be different: https://i.sstatic.net/xxYkB.png ...

Ways to modify the values of a Bootstrap Dropdown using a unique identifier

Here is an example of a typical Bootstrap Dropdown: <div class="btn-group"> <button type="button" class="btn btn-lg btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Default option<span class ...

Include vue-videobg in Vuetify using CDN without the need for webpack

I am trying to integrate vue-videobg into vuetify using a CDN without any additional requirements like "magic_videobg_to_install.java.css.js.htm" <!DOCTYPE html> <html> <head> <link href="https://fonts.googleapis.com/css?family=R ...

Is there a way to simplify and optimize the code further?

Here is the code snippet from my index.blade.php: HTML @foreach($sesis as $sesi) <td>{{ $sesi->waktu }} <label class="switch switch-text switch-info switch-pill" id="label-switch{{ $sesi->id } ...