Implement a Threejs labeling method using JavaScript

My knowledge of JS is limited, but I am eager to use JS functions to create labels for Three.js functions.

Check out the Demo Link

It seems like I'm struggling to create individual labels for each vertex in this scenario. Why does it only generate one label?

update_labels:

function update_labels( vpos ) {

var pos = get_screen_xy( vpos , camera );

note.style.display = 'block';

if ( pos.x >= x_max ) {
note.style.left = '';
note.style.right = x_max - pos.x;
} else {
note.style.right = '';
note.style.left = pos.x;
}

if ( pos.y == y_max ) {
note.style.top = '';
note.style.bottom = y_max - pos.y;
} else {
note.style.bottom = '';
note.style.top = pos.y;
}
}

get_screen_xy:

function get_screen_xy( position, camera ) {
var pos = position.clone();
projScreenMat = new THREE.Matrix4();
projScreenMat.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
pos.applyProjection( projScreenMat );

return { x: ( pos.x + 1 ) * window.innerWidth / 2,
y: ( - pos.y + 1 ) * window.innerHeight / 2 };
}

using function:

function getpos1(){
var notepos1 =objects.geometry.vertices[0];
update_labels( notepos1 );
}

// additional getpos functions omitted for brevity

function animate() {
requestAnimationFrame( animate );
controls.update();
render()
}

function render() {

camera.lookAt( scene.position );
renderer.render( scene, camera );
// calling all getpos functions
}

I would appreciate any assistance in resolving this issue. Thank you!


Thank you, 2pha:

With your guidance, I was able to make progress.

However, there is a lot of repetitive code. Can we optimize it further to achieve perfection?

Here is the complete code snippet:

<html>
<head>
<title>Demo: Implementing 2D labels for 3D objects using Three.js</title>
<script src="js/three.min.js"></script>
<script src="js/TrackballControls.js"></script>
</head>
<body>

// Code for initialization and rendering omitted for brevity

</body>
</html>

Answer №1

It appears that the update_labels() function is only referencing the same note variable, causing it to move the same label each time it runs.

If you provide more information on how you create the notes, we may be able to offer better assistance.

You could try passing the specific note you want to change into the update_labels() function.


function update_labels( vpos, note ) {
    var pos = get_screen_xy( vpos , camera );

    note.style.display = 'block';

    if ( pos.x >= x_max ) {
        note.style.left = '';
        note.style.right = x_max - pos.x;
    } else {
        note.style.right = '';
        note.style.left = pos.x;
    }

    if ( pos.y == y_max ) {
        note.style.top = '';
        note.style.bottom = y_max - pos.y;
    } else {
        note.style.bottom = '';
        note.style.top = pos.y;
    }
}

Call the function like this:


update_labels( notepos1, note1 );
update_labels( notepos2, note2 );

Don't forget to accept answers for your questions as well, as it seems you have received responses but haven't marked any as accepted yet.

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

Designing an interactive HTML table that adapts to various screen

Currently utilizing Bootstrap to create a responsive HTML table on smaller devices like the iPad, but seeking a more polished and professional alternative. Searching for a JQuery/JavaScript or CSS solution without relying on plugins. Would appreciate any ...

Inquiring about the rationale behind using `jquery.ui.all.css` specifically

I'm curious about the impact of jquery.ui.all.css on Tabs As soon as I remove it, <link rel="stylesheet" href="jquery/dev/themes/base/jquery.ui.all.css"> My tabs stop functioning. Here's my query: What exactly does the jquery.ui.all.cs ...

What is the reason behind the Placeholder not functioning in IE8?

Whenever I trigger the onblur event on an input of type "password", it will hide both the placeholder text and the input itself. Check out the GitHub link for this plugin ...

Material UI: Easily adjusting font size within Lists

When developing forms with react js and material UI, I encountered an issue with changing the font size within lists to achieve a more compact layout. The code fontSize={10} didn't seem to have any effect regardless of where I added it. Is there a wa ...

Tips for establishing expiration and validation rules for JSON web tokens

There is an issue with the token expiration time calculation. The comparison of both dates shows that the token would expire in around 17 hours, which is incorrect. It should actually only be 1 minute longer from the time of generation. I would greatly ap ...

Ways to verify user login through jQuery post method

I am currently working on a login test application that utilizes jQuery post and PHP. I'm encountering an issue where the application is able to read the input values but fails to send the data to server.php and consequently does not return any data. ...

Unable to sort the list items when utilizing the load() function

I have multiple li elements within a ul and I am using the following code to sort them in ascending order based on the data-percentage attribute: $(function() { $(".alll li").sort(sort_li).appendTo('.alll'); function sort_li(a, b) { re ...

Inquiry about unbinding in jQuery

Is it possible to use jQuery unbind() in conjunction with live()? For example: $(".content_media").unbind("touchstart").live("touchstart",function(){....}); If so, what does it actually mean? I am trying to understand the concept of unbinding elements. ...

The Ashima Perlin noise shader seems to be malfunctioning on newer releases of Three.JS

Seeking help on SO as a final attempt to resolve an issue with the latest Three.JS, as my Google searches have turned up empty. I am working with the Ashima Perlin noise shader (examples here) - Everything runs smoothly with version 48 of Three.JS, but w ...

Leverage webpack to consolidate multiple ES6 classes into a single file for easy importing via a script tag

For the past three days, I've been grappling with webpack in an attempt to complete a simple task that could have easily been done manually. However, I am determined to learn webpack for scalability reasons... I come to you now with a desperate quest ...

After generating the token, where is the appropriate place to define the authorization header?

I am currently working on implementing a security system based on tokens. The challenge I am facing is determining the appropriate location to set the authorization header after generating it, in order to validate it across all of my different routes. Belo ...

Troubleshooting the issue of AJAX not successfully transmitting variables to PHP

let xmlhttpRequest; if (window.XMLHttpRequest) { xmlhttpRequest = new XMLHttpRequest(); } else { xmlhttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttpRequest.open("POST", "test.php", true); xmlhttpRequest.setRequestHeader("Content-typ ...

Error: The function expressValidator is not recognized in the current environment. This issue is occurring in a project utilizing

I am currently working on building a validation form with Express and node. As a beginner in this field, I encountered an error in my console that says: ReferenceError: expressValidator is not defined index.js code var express = require('express& ...

Ways to display the result in a new tab

I am using colorbox with a form that will be submitted to another website. I would like for the response from that web page to load in a new tab with a new URL. ...

By executing array1.splice(1,1), I am deleting elements from array2 that was generated by copying array1 with array1.slice(0)

I was working with JSON data and converted it into an array of objects. Then, I assigned that array to another array using the .slice(0) method. However, I encountered an issue where when I tried to remove an element from the assigned array, it also remov ...

What could be causing my CSS transitions to fail when using jQuery to add classes?

I'm currently working on a website and I'm facing an issue with the transition not functioning as expected. The problem persists even when the 7.css stylesheet is removed and interestingly, the transition works fine when using window:hover. My a ...

Issue on Heroku with Discord.js displaying a "Service Unavailable" message

Encountered a strange error while trying to launch my discord bot on heroku. Previously, I implemented a command handler for the bot to organize commands in separate files but faced multiple code errors. With the help of a member from this community, all e ...

Choose a single checkbox to select all options within a bs-table row

After successfully using bs-tables to pass selected rows through checkboxes, I am now faced with the challenge of sending data from all rows when just one checkbox is selected. The code below depicts my current approach for passing data of single and mul ...

The problem with React useState not updating could be due to useRef interference

I'm facing a strange issue with my React code: the useState function is not updating the view, despite trying everything to fix it. To illustrate the problem, I have created a simple example: function(){ const [enterJob, setEnterJob] = useSt ...

PayPal's Intelligent Payment Buttons: Oops! There seems to be an issue with parsing the JSON data - an unexpected character was found at line 1,

I've been racking my brain over this issue for the past two days... I've been attempting to integrate Smart Payment Buttons from PayPal, diligently following each step in the guide. However, I keep encountering the following error: Error: JSON. ...