Text positioned next to a line in three.js

Within a scene constructed from JSON data, I have a tube geometry that requires a line marker at each segment. To achieve this, I am using the centroid of a face as the starting point and adding 10 to each coordinate of the centroid for the end point of the line.

You can view an example of a tube with a line here.

Below is the code snippet for adding a line from the center of a face:

var lineGeo, lineMat, line;
var fx = tube.faces[3].centroid.x;
var fy = tube.faces[3].centroid.y;
var fz = tube.faces[3].centroid.z;
lineGeo = new THREE.Geometry();
lineGeo.vertices.push(new THREE.Vector3(fx, fy, fz), new THREE.Vector3(fx+50, fy+50, fz + 50));

lineMat = new THREE.LineBasicMaterial({color: 0x000000, lineWidth: 2});                 
line = new THREE.Line(lineGeo, lineMat);
line.type = THREE.Lines;
tubeMesh.add(line);

My next challenge is how to add text at the end of a line. In a live environment, the tube consists of 2000 coordinates with 200 lines serving as markers. I need to include text at the end of each marker (line).

Answer №1

If you want to add text to a plane in your 3D model, one way to do it is by taking the coordinates of your line, adding an offset, and creating a plane just above it. This plane can then display a texture with your desired text on it. You can adjust the opacity parameter as needed.

There are a few ways to create these textures:

1) Import all your text as images (although this may not be feasible for large amounts of text).

2) Use a canvas element to draw text using CSS, which can then be used as a texture for the plane. This method is recommended to avoid slowing down the rendering process with real-time dynamic text generation.

Here's how you can implement this:

texture_placeholder = document.createElement( 'canvas' );
texture_placeholder.width = 100;
texture_placeholder.height = 20;

Add text to the canvas:

var context = texture_placeholder.getContext( '2d' );
context.fillStyle = '#f00'; 
context.textAlign = "center";
context.textBaseline = "middle";           
context.font = ' bold 150px';             
context.fillText('This is the 3rd face!', texture_placeholder.width / 2, texture_placeholder.height / 2);

Create the texture based on the canvas:

var texture = new THREE.Texture( texture_placeholder );
texture.needsUpdate = true;
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: true, side:THREE.DoubleSide } );

Finally, set up the mesh for the plane:

var plane = new THREE.PlaneGeometry( 100, 20 );
var text = new THREE.Mesh( plane, material )

For an example, you can check out this link. Hope this helps!

Answer №2

If you're looking for a detailed guide on creating a textured image in Three.js using text, this example is worth checking out:

Feel free to explore and see if it meets your needs!

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

Generating Excel keys: duplicating/inserting cells among current columns for 1500 sets of data

I have the challenge of aligning different subtypes of data from two separate sets next to each other. Currently, each set of data is in its own rows with 1500 columns. To intersperse them, I've been manually moving cells from below up in between the ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

How can one obtain the object (whether it be a string or an array) named NAME?

Can someone help me create a prototype like this: Array.prototype.getName=function(){ [...]return arrayName; } Then I want to be able to do this: x = new Array; alert(x.name); and have "x" displayed in the alert. I'm currently developing on Chrom ...

If the visitor navigated from a different page within the site, then take one course of action; otherwise

How can I achieve the following scenario: There are two pages on a website; Parent page and Inside page. If a user navigates directly to the Inside page by entering the URL or clicking a link from a page other than the Parent page, display "foo". However, ...

Having trouble adding space between paragraphs inside a div element while trying to retrieve its content using jQuery

Issue Description: Currently, I am utilizing the jQuery syntax below to count words: var value = $('#displayContent').text(); Before counting the words, I aim to employ a RegExp in value that concatenates the last word of each sentence with th ...

Identifying edited files within the node_modules directory: A comprehensive guide

While working with the serverless framework, I installed it using npm. During my debugging process, I made some modifications by adding console.log statements to different files within the node_modules folder. Unfortunately, I can't recall which speci ...

What are the limitations of sorting by price?

One issue I am facing is that the sorting functionality in the sortProductsByPrice (sortOrder) method doesn't work properly when products are deleted or added. Currently, sorting only applies to products that are already present in the this.products a ...

Initializing Access Model in Sails.js Service启

The inquiry: In the context of sails.js, it appears that Services are initialized before Models during the initialization process. Is there a way to alter this sequence? Can Models be loaded before Services? If not, then how can one retrieve specific se ...

Exploring the different pages in React js

I am currently working on implementing a button in React Js that, when clicked, should navigate to another screen. However, I keep encountering an error: TypeError: Cannot read property 'push' of undefined. I have tried various solutions but noth ...

Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango" let fruitArray = [{fruit:"apple",locale:"US"}, {fruit:"orange",locale:"US"}, {fruit:"banana",locale:"US"}, {fruit:"apple",locale:"US"}, {fruit:"orange",locale:"IT"}, {fruit:"apple",locale: ...

Leveraging JavaScript and HTML to extract a single data point from a JSON response

As a complete beginner, I want to clarify that I may not be using the correct terminology in my question. I am embarking on creating an HTML5/Javascript application with Intel XDK to retrieve barcode information for video games from an online API. Specifi ...

There was an error thrown: Unable to access properties of an undefined value (specifically trying to read 'first')

Yesterday, my sister requested me to add a language change button to her website for some text. However, upon implementing it, I encountered the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'first'). Despite t ...

Guide to Winston MongoDB: Distributing logs across multiple collections rather than aggregating them all into one collection

Is it possible to configure winston-mongodb to log to multiple collections simultaneously? var winston = require('winston'); require('winston-mongodb').MongoDB; var logger = new winston.Logger({ level: 'info', transport ...

How can I prevent event propagation in Vuetify's v-switch component?

Currently, I am working with Vuetify and have incorporated the use of v-data-table. Whenever I click on a row within this data table, a corresponding dialog box represented by v-dialog should open. Additionally, each row contains a v-switch element. Howeve ...

How to Eliminate Image Flickering While Loading in a React Component

Currently, I am developing a React component that takes an imageUrl and displays it on a canvas with a deliberate 2-second delay to mimic loading time for larger images. However, I have encountered a problem: when the imageUrl changes in the parent compone ...

What is the best method to extract values from an array?

In my array, I am storing multiple values together such as: var locations = [ 'Bhopal','Mobile',new google.maps.LatLng(18.40,78.81),'images/mobile.png', 'Bangalore','Television',new google.maps.Lat ...

Empty value retrieved from dropdown selection

My usual method of populating a Dropdown with JavaScript involves the following code: function populateDropdown(ddl_id) { var option_str = ""; var x; for(x in dataList){ option_str += " <asp:ListItem Value='" + dataList[x] + "' Text=&ap ...

What is the best way to sort inertia data on the client-side?

Looking for a solution with my component that receives data, I have the following setup in my controller: route::get('/', function() { return inertia('foo', ['data' => Model::all()]) }); Within my Vue component: <templa ...

What is the best way to establish a default selection in Angular?

After retrieving JSON data from the server, it looks something like this: $scope.StateList = {"States": [ { "Id": 1, "Code": "AL", "Name": "Alabama" }, { "Id": 2, "Code": "AK", "Name": "Alask ...

Here's a new version: "Strategies for deactivating a text field in a desktop application that

I am currently using WiniumDriver to automate a desktop application. My goal is to disable a text field once a value has been entered into it. // Launch the desktop application WiniumDriver driver = null; DesktopOptions option = new DesktopOptions(); o ...