Creating interactive shapes in a 2D scene using Three.js and custom attributes

Recently, I created a 2D floorplan drawing using three.js.

The shape was incorporated into the drawing with the following code snippet:

var geometry = new THREE.Geometry();
geometry.vertices.push(
    new THREE.Vector3(50, 0, 90),
    new THREE.Vector3(130, 0, 95),
    new THREE.Vector3(74, 0, -50)
);
geometry.faces.push(new THREE.Face3(0, 1, 2));

var material = new THREE.MeshBasicMaterial({ color: 0xff0000,opacity:0.9 });
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
mesh.on('click', function (ev) {
    console.log(ev);
 });

I am currently working on adding a shape/geometry with partial opacity to the scene and enabling user interaction by allowing them to click on it. Upon clicking, I aim to trigger a JavaScript function on the webpage that retrieves a unique ID along with other custom attributes or properties of the clicked shape.

For handling events, I have opted for three.interaction.

My main challenge lies in determining where to store object attributes and how to access them. Can this be achieved within three.js? Furthermore, I am curious if there exists a method to customize the appearance of the clickable object upon hovering, such as changing its color?

Answer №1

After some experimentation, I have successfully included additional properties in the userData field of the object:

var geometry = new THREE.Geometry();
geometry.vertices.push(
    new THREE.Vector3(50, 0, 90),
    new THREE.Vector3(130, 0, 95),
    new THREE.Vector3(74, 0, -50)
);
geometry.faces.push(new THREE.Face3(0, 1, 2));

var material = new THREE.MeshBasicMaterial({ color: 0xff0000, opacity: 0.9 });
var mesh = new THREE.Mesh(geometry, material);
mesh.userData.code = "12345ABC";
mesh.userData.name = "Example01";
scene.add(mesh);

mesh.on('click', function (ev) {
    console.log(ev.target.userData.code);
    ev.target.material.color.setHex(0xffff00);
});

In addition, I discovered that I could change the color using mouseover and mouseout events by implementing ev.target.material.color.setHex(0xffff00).

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

When I utilize $router.push() to navigate to a different page, the back button will take me back to the previous page

Within my Vue project, there is an HTML page that I am working on. Here is the link to the page: https://i.sstatic.net/cbtqM.png Whenever I click on the "+"" button, it redirects me to this specific page: https://i.sstatic.net/0rmMD.png This page funct ...

What is the best way to remove a component from MongoDB after a specified period of time has passed

I am currently working on a basic web application using Node.js and MongoDB. I'm struggling with deleting entries from this field: shows what my webpage looks like After entering some data and clicking the button, it creates a new collection in my Mo ...

Hold off until the asynchronous function has completed - Ionic2

I am developing in Ionic2 and encountering an issue: Within my component, there is a method called drawPlayer that fetches data from a Firebase database. Here is the code for this method: drawPlayer(){ this.playerData.drawThePlayer().on('value&a ...

Does getServerSideProps execute for each page request, or solely for HTTP requests?

Does getServerSideProps execute with every page request, or is it specifically for HTTP requests? ...

Can you utilize aframe-physics-system in A-Frame to manipulate cannon elements using JavaScript?

In my A-Frame scene, I am utilizing three.js to generate objects such as: var boxMaterial = new THREE.MeshPhongMaterial( { map: boxTexture, side: THREE.BackSide, bumpMap: boxBumpMap } ); var boxGeometry = new THREE.BoxBufferGeometry( 20, 20, 20 ); var bo ...

Storing a table structure in a variable using JavaScript

Kindly review this arrangement: 1 | 2 | 3 | .... ---------------------------------------------------------- 2016 100 2000 500 2015 540 450 1200 2014 120 230 660 I am seeking a method ...

Corrupted PDF file after attempting to download through AJAX

Currently, my method involves making an API call (using cURL on the server-side) to fetch an XML file. Inside this XML file is a base64 encoded PDF, which I then extract and save on the server for future downloading. The process goes like this: <?php ...

Storing HTML values in a Meteor database is a common practice for web

Within my meteor project, I have a paragraph in HTML containing a JSON value as follows: {"Active Template Id":"6467","Shirt Brand":"levis","ProductId":"EB301","Brand":"on","Material":"cotton","Price":"1800","Combo Id":"S90"} I am looking to store this v ...

Reorganizing Arrays in Javascript: A How-To Guide

I have an array in JavaScript called var rows. [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f4f2e4f3b0c1e4f9e0ecf1ede4afe2eeec">[email protected]</a>' }, { email: '<a hre ...

What is the reason for node-sass being rebuilt after upgrading from npm6 to npm7?

My application utilizes sass opposed to node-sass. Within my package-lock.json file, there is no mention of node-sass. I have been successfully using npm 6 for years without any issues. However, upon attempting to run npm install with npm 7, I encounter ...

Assistance requested in structuring JSON data

I'm currently working on making my javascript code more dynamic. Here's what I have so far: data.addRows(2); data.setValue(0, 0, 'name goes here'); data.setValue(0, 1, value 1 goes here); data.setValue(0, 2, value 2 goes here); data. ...

How to Assign a Specific ID to the Body Tag in Wordpress Using functions.php

Struggling to find a simple solution after scouring the web for answers. Most tutorials are overly complicated. I'm attempting to integrate a jQuery menu system into my Wordpress site and want to assign a unique body ID to make targeting easier. I p ...

Storing form data in a file using React

I am trying to create a feature in my react component where instead of submitting a form and sending the data, I want to write this data to a file for later use. Is it achievable using vanilla JS or should I consider using a library? This is how my handl ...

A JavaScript code snippet that stores the total number of bytes read from a CSV file in a variable

I currently have a CSV file located on a web server that is regularly updated with numeric and string data of varying lengths. I am seeking a solution to calculate the total byte values of each row when reading the file, as the byte count is crucial due ...

When running tests in Jest, the error "TypeError: _enzymeAdapterReact.default is not a constructor

I'm encountering an issue while testing a react-native component with jest and enzyme TypeError: _enzymeAdapterReact.default is not a constructor Below are my development dependencies: "@babel/core": "^7.12.10", "@ba ...

The issue of Django and Ajax not automatically updating data

A Save button has been developed. When the user clicks the "Save" button, a record is saved to their collection, changing the button text to "Saved". The user can then click on "Saved" to unsave the record. The record can be successfully saved, and the aj ...

Choose Default Value in Drop-Down List in AngularJS when Page Loads

Within the realm of Angularjs, there exists a DropDown: <select ng-model="category" ng-change="categoryChanged(category)" class="form-control" data-ng-options="category as category.name for category in categories"> <option value="">Se ...

In JavaScript, when a condition is met, two strings are produced but only the last string is printed

My for loop with nested arrays is working fine, but it should display two strings and only shows the last one. for (i = 0; i < $scope.taskGroups.length; i++) { for (j = 0; j < $scope.taskGroups[i].tasks.length; j++) { ...

Instructions for navigating to the dashboard component page in vue js after a successful login process within the login component

Greetings! I am currently working on setting up routing for my login component page to redirect to the dashboard component upon successful login. I have managed to receive responses from my local API with status codes 400 and 200 but I am unsure how to h ...

Webpack resolve.alias is not properly identified by Typescript

In the Webpack configuration, I have set up the following: usersAlias: path.resolve(__dirname, '../src/pages/users'), In my tsconfig.json, you can find: "baseUrl": ".", "paths": { "usersAlias/*": ["src/pages/users/*"], } This is how the cod ...