What is the best way to add clickable links to 3D objects and meshes with ThREE?

My goal is to create a simple box that can act as a link when clicked. This seemingly straightforward task has proven difficult for me, so I would greatly appreciate any assistance. Despite my efforts to troubleshoot and research online, I have not been able to determine where I went wrong. While scouring Stack Overflow, I only found two similar questions, but they did not provide the answers I needed.

const coolTexture = new THREE.TextureLoader().load('cool.jpg');
const cool = new THREE.Mesh(
  new THREE.BoxGeometry(3, 3, 3),
  new THREE.MeshBasicMaterial({
    color: Math.random() * 0xffffff
  })
);

cool.userData = {
  URL: "http://stackoverflow.com"
};
scene.add(cool);

function linki() {
  if (intersects.length > 0) {
    window.open(intersects[0].object.userData.URL);
  }
}

document.body.onclick = linki

Answer №1

If you only have one box to work with, simply use window.open(object.URL); when the pointerdown event is triggered.

let scene, camera, renderer, cube;

window.addEventListener("pointerdown", () => {
  window.open(cube.URL);
});

//

function initialize() {
  // Initialization code
}

initialize();
body {
  font-family: sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.145.0/three.min.js"></script>
<!DOCTYPE html>
<html>

<head>
    <title>Unique Title</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app"></div>

    <script src="src/index.js">
    </script>
</body>

</html>

However, if you are planning on creating multiple URLs, utilizing a Raycaster and checking which box was clicked would be more appropriate.

let scene, camera, renderer;
let objsToTest = [];

// Additional unique JavaScript code

init();
body {
  font-family: sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.145.0/three.min.js"></script>
<!DOCTYPE html>
<html>

<head>
    <title>Unique Title</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app"></div>

    <script src="src/index.js">
    </script>
</body>

</html>

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

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

Check to see if the moment function has been executed and if the resulting output is accurate

I have a function called moment that formats a date received from the server in milliseconds. I am attempting to write tests using Enzyme and Jest to check if the moment function has been called (1), and whether the output of the function matches the expec ...

JavaScript program that continuously reads and retrieves the most recent data from a dynamically updating JSON file at regular intervals of every few seconds

I am a beginner in JavaScript and I'm facing an issue with displaying the most recent values from a .json file on an HTML page. The file is updated every 10 seconds, and I am also reading it every 10 seconds, but I'm not getting the latest data. ...

What is the best way to retain data after clicking a button?

I am facing an issue where I need to figure out how to add information to a new page when a button is clicked. For example, let's say I have an "add to cart" button and upon clicking it, I want to store some data. How can I achieve this functionality? ...

Ways to tally the amount of views on a post

Currently, I am in the process of developing a website that features posts. I have included a 'Read more' link which expands the content upon clicking, similar to Quora. However, I am facing an issue - I need to track the total number of times th ...

retrieve data for chart from an AJAX request

I am looking to create a chart using amCharts and I have received some values from the server through an ajax call. Now, I need help in utilizing this data for my chart. Can anyone guide me on how to achieve this? var chart = am4core.create("chartdiv& ...

Unable to load the manually added module in the /node_modules/ folder

I'm trying to manually use a module that I placed in the /node_modules/ directory. After copying and pasting the files and installing dependencies with npm, I encountered an issue while using NWJS 0.16.0. When attempting var speech = require('sp ...

Deselect a checkbox that is already selected and choose the current option in the multiselect dropdown

I've created a code that allows for single select in a multiselect dropdown, disabling other options once one is chosen. However, I don't want to disable the checkboxes and would like to uncheck the selected option if a new one is chosen, all whi ...

What is the best way to delete a parent table row in React JS when the child "delete" button is clicked?

Struggling with hiding a table row in my React JS app upon clicking the "delete" button. The functions causing issues are: ... changeHandler: function(e) { ... }, deleteHandler: function(e) { e.currentTarget.closest("tr").style.visibility = "hidden"; } ...

The content in tinymce cannot be edited or removed

Is there a method to prevent certain content within the tinyMCE Editor from being edited or removed? While I know that adding a class "mceNonEditable" can make a div non-editable, it can still be deleted. Is there a way to make it unremovable as well? ...

Troubleshooting issues with Firebase integration in a Node.js environment

I am currently encountering difficulties implementing Firebase in my Node.js project. Below is the code snippet that I am attempting to execute on Node. var firebase = require("firebase"); var admin = require("firebase-admin"); var serviceAccount = requi ...

Exploring the functionality of Async Storage in React Native for efficient data saving purposes

I'm completely new to working with Async and async storage. I am a bit lost and unsure of how to proceed, but my main objective is to use setWorkouts() to assign workouts based on the values I retrieve from asyncstorage, and then save these workouts. ...

Cordova triggers a 500 (Internal Server Error) when making an Ajax request

When I send an ajax request, it works fine in the browser but returns an internal error when sent within a Cordova APK. Upon comparing the headers, I noticed that the only difference is in the ORIGIN: The one not working has origin: file:// POST 500 (In ...

While JSON Lint may declare the JSON data as valid, JSON.parse may still encounter an error when trying

I'm struggling to parse a simple JSON object. It's strange because when I check the validity of my JSON string on JSONLint (http://jsonlint.com/), it shows that it's valid. var data = '{"token":"9eebcdc435686459c0e0faac854997f3","email ...

What is the method for determining the height of a div element when it is set to 'height=auto'?

I am trying to determine the height of a specific div using Javascript. Here is the script I have written: function getMainDivHeight() { var num = document.getElementById('up_container').style.height; return num; } However, this script ...

Converting RSS title to HTML format with the help of JavaScript

I am currently working on populating a menu on a webpage with the 5 latest topics from our site's RSS newsfeed using JavaScript (specifically jQuery version 1.9.1). I have been searching for a solution, but most answers I find reference deprecated scr ...

How do the JavaScript thread and the Silverlight UI thread interact with each other?

While JavaScript operates on a single thread, Silverlight does not follow the same restrictions. However, when it comes to the interaction between JavaScript and Silverlight, it is crucial that communication occurs on the Silverlight UI thread. The relati ...

Making changes to the retrieved properties using Apollo GraphQL within a Vue.js environment

I'm trying to utilize the Moment javascript library to format a date that I retrieve through Apollo-GraphQL. My setup involves VueJS Apollo on the client side for executing graphQL queries like this: import { ALL_EVENTS } from '../constants/grap ...

Provide input to npm when running "my command" and utilize that input within my functions

Consider the contents of app.js const { doCoolStuff } = require("./api/myApi"); // grab parameter from command line and store it in "myParam" doCoolStuff(myParam); ... // more code And Package.json: { "name": "------ ...

Using an id as the attribute value for a React ref

I have a question about referencing DOM nodes in a component. Currently, I am able to get the nodes and children using the following code: export class AutoScrollTarget extends React.Component { constructor(props) { super(props); this ...