Utilize three.js to showcase texts at various coordinates on the screen

I have a requirement to showcase various texts at different coordinates using three js. My goal is to present the text in a similar layout as shown in the provided image file below.

I am seeking a function that can accurately position text at varying locations, akin to the reference image.

https://i.sstatic.net/rPIAu.png

Javascript

var container, camera, scene, renderer, controls;
var text2;


init();
animate();

function init(){

    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.01, 1000 );
    camera.position.z = 1 ;

    scene = new THREE.Scene();

    text2 = createLabel("Tower",30,90,30,10,50,"blue","white");
    text3 = createLabel("Hello",30,90,50,60,50,"black","white");
    text4 = createLabel("Tower",30,90,120,100,50,"red","white");

    console.log( text2 );

    scene.add( text2 );
    scene.add( text3 );
    scene.add( text4 );
    text2.lookAt( camera.position );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setClearColor(0xffffff);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.append( renderer.domElement );

}

function createLabel(text, x, y, canvasPosition_x,canvasPosition_y, size, color, backGroundColor, backgroundMargin) {

    var canvas = document.createElement("canvas");

    // set resolution

    canvas.width = 512;
    canvas.height = 512;

    var context = canvas.getContext("2d");
    context.font = size + "pt Arial";

    context.font = size + "pt Calibri";
    context.fillStyle = "white";

    canvas.position = "absolute";

    context.fillRect( 0, 0, canvas.width, canvas.height );
    context.fillStyle = color;
    context.fillText( text, x, y );
    context.position = "absolute";

    var texture = new THREE.CanvasTexture( canvas );

    var material = new THREE.MeshBasicMaterial({
            map: texture,
    // color: 0xff0000 
});

    var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry(), material);

     mesh.position.x = canvasPosition_x;
     mesh.position.y = canvasPosition_y;

    return mesh;

}

function animate()  {

    requestAnimationFrame( animate );
    renderer.render( scene, camera );


}

View Demo on JSFiddle

Answer №1

To adjust the position of the mesh, simply modify its position attribute. For example, set mesh.position.x = 0.5;.

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

Utilizing the ng-controller directive multiple times on DOM elements within an Angular application

I am facing an issue where I need to use the same controller on two DOM elements. After some research, I found out that using ng-controller on two elements will create two separate instances of the controller. To address this, I decided to share a variable ...

Why isn't my function being triggered by the Click event?

I can't figure out why the click event isn't triggering the btn() function. function btn() { var radio = document.getElementsByTagName("input"); for (var i = 0; i > radio.length; i++){ if (radio[i].checked){ alert(radio[i].value); } ...

Disabling dates in the second datetimepicker depending on following days selected in the first one

I have implemented the bootstrap date picker and I am using two textboxes for searching by date range. I want the second textbox to display the days after the date selected in the first textbox. Any suggestions would be appreciated. Here is the HTML code: ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

Leveraging asynchronous data in a synchronous manner

I am dealing with tax rate data stored in the database to ensure easy updates when necessary. However, JavaScript's asynchronous nature complicates accessing this data as it requires promises or callbacks to retrieve query results. Is there a solution ...

The function responsiveTable does not exist

I recently added the following code to my aspx page: <script src="../Scripts/jquery.responsivetable.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#grdStudent').responsiveTable( ...

Is there a way to retrieve all the selected values from multiple select inputs when a button is clicked in React?

I am currently working on developing a questionnaire where the select inputs' values are collected and averaged to generate a final score. Although it may sound simple, I'm facing difficulties in retrieving these values. At this point, my primary ...

"Calculating the total value of an array based on its individual elements

My API response includes committers to a git project, but some members are repeated because they share the same name with different email addresses. Example response: [ {"id": "122334", "name": "bob", "commits":10, "email": "<a href="/cdn-cgi/l/emai ...

What is the best way to incorporate animations for the initial page load?

https://i.sstatic.net/ZwSww.pngIs there a way to add animations during the initial page load in Next Js? I would like to have a series of blocks displayed in gray with a loading animation before the actual content appears. Are there any libraries availab ...

Generating a variety of Audio Tags within a container and streaming MP3 files

I have an ajax request that retrieves base64 Mp3 data from my database. When I successfully retrieve a single base64 data, I am able to play the mp3 using an audio tag. However, when I receive multiple base64 data entries, I need to create and link each ...

what is the way to send arguments with the rest parameter in javascript?

Here is the function call I need help with: await this.myFunction({'fields.page': page, ...filters}); This is my function code: async myFunction({state, commit}, filters) { const {items} = await fetchData({content_type: state.contentType, ...fi ...

The masonry plugin overlays images on top of each other

I have gone through similar questions but haven't found anything that applies to my specific case. Following an ajax call, I am adding li elements to a ul $.ajax({ url: 'do_load_gallery.php?load=all' }).done(function(result) { ...

Creating a new bookmark in Firefox without encountering a pop-up dialog box

I am curious if it is feasible to utilize JavaScript to add a bookmark in Firefox seamlessly, without triggering any dialog box. Essentially, can I have the user click on a link and have the bookmark generated automatically, bypassing any additional step ...

The issue of Access-Control-Allow-Origin restriction arises specifically when using the gmap elevation API

My attempts to retrieve the elevation of a site using latitude and longitude have been unsuccessful due to an error I encountered while making an ajax call. Regardless of whether I use HTTP or HTTPS, I receive the following error message: "No 'Access ...

How does the Express next() function trigger the execution of the following middleware?

Can someone please explain how the next() function is able to call the subsequent middleware or route? I've searched everywhere but can't seem to find a good resource with the actual code. If anyone could share where I may find this information, ...

Show Text When Clicking Within Separate DIVs

I have a set of three divs. One contains a Twitter icon, another holds a LinkedIn icon, and the last one is designated for displaying text upon clicking. My goal is to click on the Twitter icon and have corresponding text appear in the third div. Then, if ...

The error message "expressValidator is not a function" indicates a problem within the Express

I'm encountering an issue while trying to set up and utilize the express-validator package. I have successfully installed version 6.0.0 of the package and included the following code in my server.js file: const bodyParser = require('body-parser& ...

What is the best method to dynamically filter an oData call based on dates?

Whenever I make an AJAX call, I typically use a URL structure like this: http://somecomputer/Service.svc/Method?$filter=SomeDate gt DateTime'2014-08-24' This method has been effective for me so far, but I'm curious if there's a way to ...

The JSON object, which has been converted into a string and sent over the network,

Attempting to set up a websocket server using TypeScript in Node.js, the following code was used: ws.on('message', (msg: string) => { console.log("got message:" + msg); const m = JSON.parse(msg); console.log(m); ...

What steps should I take to ensure a local HTML page retains the current section that is hidden open whenever it is reloaded?

One of the challenges I have encountered with my local HTML note-taking file is that, despite dividing it into hidden sections accessible by clicking on buttons at the top of the page, reloading the content resets it back to its default state. This means t ...