Utilizing For Loop to Integrate TextGeometry in THREE.js

Attempting to construct numbers along a 3D grid using THREE.TextGeometry()

However, only one number is being generated. How can I fix this issue?

The "current" variable ranges from -10 to 10, excluding 0. My IDE (PyCharm) is indicating that the "Mutable Variable is accessible from closure"

I'm unsure of what mistake I am making and how to resolve it. Thank you

function createGridNumbersX(size){

var grpGridNumbersX = new THREE.Group();
grpGridNumbersX.name = 'grpGridNrsX' ;

var loader = new THREE.FontLoader();
var fontType = 'fonts/helvetiker_regular.typeface.json';
var textMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff});

for (i=0; i<(size*2)+1; i++) {

    var counter = i + 1;
    var start = -size - 1;
    var current = start + counter;

    if (i === size) {
        continue
    }

    console.log('current ' + current);

    loader.load(fontType, function (font, ) {

        var textGeometry = new THREE.TextGeometry(**current**, {
            font: font,
            size: 0.3,
            height: false,
        });

        var mesh = new THREE.Mesh(textGeometry, textMaterial);
        mesh.name = 'xNr' + i;
        mesh.position.x = current;

        grpGridNumbersX.add(mesh);

    });
}

scene.add(grpGridNumbersX);

} createGridNumbersX(10);

Answer №1

It's probable that you'll have to wait for the font to load just once.

var grpGridNumbersX = new THREE.Group();
grpGridNumbersX.name = 'grpGridNrsX' ;

var loader = new THREE.FontLoader();
var fontType = 'fonts/helvetiker_regular.typeface.json';
var textMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff});
loader.load(fontType, createText);

function createText(font) {
    for (let i=0; i<(size*2)+1; i++) {

        var counter = i + 1;
        var start = -size - 1;
        var current = start + counter;

        if (i === size) {
            continue
        }

        console.log('current ' + current);

            var textGeometry = new THREE.TextGeometry(**current**, {
                font: font,
                size: 0.3,
                height: false,
            });

            var mesh = new THREE.Mesh(textGeometry, textMaterial);
            mesh.name = 'xNr' + i;
            mesh.position.x = current;

            grpGridNumbersX.add(mesh);
    }

    scene.add(grpGridNumbersX);

} 

You may discover this answer helpful. It also generates one mesh per letter, arranging them into a ring instead of a grid.

Answer №2

The Resolution: * Implement the "For Loop inside the Loader.load" * Change the "current variable to a string"

Still figuring out how to align each number with the camera, it works correctly when I first load the scene, but the lookat functionality doesn't update when I move the camera

function generateGridNumbersX(size) {

var gridNumsX = new THREE.Group();
gridNumsX.name = 'grpGridNrsX';

var loader = new THREE.FontLoader();
var fontType = 'fonts/helvetiker_regular.typeface.json';
var textMaterial = new THREE.MeshBasicMaterial({color: 0xffffff});

loader.load( fontType, function (font) {

    for (i=0; i<(size*2)+1; i++) {

        var count = i + 1;
        var startVal = -size - 1;
        var currentVal = startVal + count;

        if (i === size) {
            continue
        }

        var strVal = currentVal.toString();

        var textGeometry = new THREE.TextGeometry(strVal, {
            font: font,

            size: 0.2,
            height: false,
        });

        var txtMesh = new THREE.Mesh(textGeometry, textMaterial);
        txtMesh.position.x = currentVal;
        txtMesh.name = 'xAxeNr' + i;
        txtMesh.lookAt(camera.position);


        gridNumsX.add(txtMesh);
    }
});


scene.add(gridNumsX);

} generateGridNumbersX(10);

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

A method for transforming each word in a string to begin with a capital letter

I'm not sure if my approach to solving this problem is correct: function capitalizeFirstLetter (string) { let stringArray = string.split(' '); for (let i = 0; i < stringArray.length; i++) { let firstLetter = stringArray[i ...

What is the best way to create a table of buttons with seamless integration, leaving no gaps between each button?

While developing a website, I encountered an issue where I couldn't figure out how to eliminate gaps between buttons. Despite searching online for a solution, I struggled to articulate my problem clearly. Essentially, I am trying to create a table lay ...

The ajax method for loading an xml file results in displaying the undefined message

When attempting to fetch content from an xml file using ajax, the page initially displays "undefined". However, upon refreshing the page, the content loads successfully. Take a look at my code snippet below: $.ajax({ type: "GET", url: "xm ...

Customizing the toolbar in MUI Datatable

Is there a way to customize the MUI-Datatable by moving the block within the red square into the toolbar and filling up the empty space? I could use some help with this task. ...

Error message HMR Webpack was found to be invalid

When using Webpack, I keep encountering the following error message: Invalid HMR message, along with a lengthy JSON string. Unfortunately, I couldn't find any helpful resources to assist me in debugging this issue. Do you have any suggestions? https ...

Do I need to implement server side rendering in Vue or React to secure my REST API?

When my REST API is located on the same machine as the SSR of Vue or React (NUXT, NEXT), is it still necessary to secure the API? ...

Integrating a Find Pano functionality into a Kolor Panotour

I used a program called Kolor to create a panorama. Now, I am attempting to integrate the "find pano" feature, which involves searching through the panoramic images for display purposes. I have come across an HTML file that contains the search functionalit ...

Creating aesthetically pleasing URLs from data: A simple guide

Can someone help me transform this data into a pretty URL? I am looking for something similar to Appreciate the assistance! :) var x = {data1, data2, data3}; $.ajax({ url: 'https://mywebsite.com/admin/leads/count/', data: x, type: &a ...

Should one use Javascript library dependencies with or without bundling?

I'm in the process of packaging a library so that it can be utilized in two different ways: <script src="myLib.js"/> as well as mylib = require('myLib') However, myLib relies on several other libraries, some of which I believe the ...

Is there a way to incorporate both max-width and min-width in a matchMedia query effectively?

I'm currently utilizing the matchMedia API in my JavaScript code to identify viewports, with the goal of reducing DOM manipulations. Instead of using display: none extensively, I am opting for a v-if directive from Vue to determine when elements are ...

Retrieve information from Google Sheets to use in SVG map

While working on a local HTML page, I encountered an issue with my script. I am using the svgMap library to create a map of movies I have seen, pulling data from a Google Sheets document using the opensheet library. The JSON output looks like this: [{"Coun ...

Am I going too deep with nesting in JavaScript's Async/Await?

In the process of building my React App (although the specific technology is not crucial to this discussion), I have encountered a situation involving three asynchronous functions, which I will refer to as func1, func2, and func3. Here is a general outline ...

No result returned by IntersectObjects function

Recently, I've been delving into the world of three.js to determine if a ray intersects with an object. My scene is all set up and looking great! I tried clicking on the sphere that I created using the following code: var intersected_objects = []; ...

Setting up Firebase in an Angular 6 project without using AngularFire

While working on a project, I initially set up Firebase using AngularFire but found that I didn't need to use many of its functions. Instead, I imported firebase/app in each service and directly used specific functions like firebase.auth() and firebas ...

Passing an ID in Next.js without showing it in the URL

I am looking to transfer the product id from the category page to the product page without showing it in the URL Category.js <h2> <Link href={{ pathname: `/product/car/${title}`, query: { id: Item.id, }, }} as={`/p ...

Assigning the image source to match the image source from a different website using the image ID

Would it be possible to retrieve the URL of an image from a different webpage using its img ID, and then implement it as the image source on your own website? This way, if the image is updated on the original site, it will automatically update on yours as ...

Patiently awaiting the completion of the entire page loading process

When using the methods below, we can determine if the entire page has finished loading. Sys.sleep(5) or remDr$executeScript("return document.readyState == 'complete';") or remDr$setTimeout(type = "page load", milliseconds = 10000) However, ...

Adjust the size of the sliding tool with images of varying dimensions

My mobile-first slider features three different types of images: tall, horizontally long, and square. I want the size of the slider to be determined by the horizontally long image and then scale and center the other images to fit its size. To achieve this, ...

Having trouble drawing two lines in Highcharts? Is the JSON format invalid?

I am attempting to plot 2 lines on a graph using Highcharts. The PHP server-side file is as follows: require_once('Connections/conexion.php'); $sesionUser = $_SESSION['MM_Username']; $sesionIdGrupo = $_GET['idGrupo']; $sesio ...

The datepicker UI triggers the onChangeMonthYear event before executing the beforeShowDay function

I am currently using the jQuery Datepicker UI (http://jqueryui.com/datepicker/) My goal is to dynamically color specific days based on data retrieved from an AJAX call. This is the current setup: $(document).ready(function() { getAllDays(); $("# ...