Methods for loading a font just once? (TypeScript / Three.JS)

My goal is to generate 20 text blocks, all using the same font. However, I encountered an error with the new TextGeometry if the font isn't loaded yet.

Currently, I have been creating each text block like so:

new THREE.TextGeometry(this.text, {
    font: Object(response) as THREE.Font
} as THREE.TextGeometryParameters);

within this block of code:

let fontLoader = new THREE.FontLoader();    
fontLoader.load('/fonts/my_font.json', response => {

This approach is not efficient since it requires loading the font 20 times (once for each new text block), causing delays during execution, especially when testing.

I would prefer to load the font only once and save it in a variable, but I don't know how to ensure that it's fully loaded before generating the TextGeometry.

I'm wondering if Observables could help with this issue?

Your insights and suggestions would be greatly appreciated!

Answer №1

As an illustration, you can achieve this by following these steps:

let manager = new THREE.LoadingManager();
manager.onLoad = function() { // once all resources have loaded
  initialize();
  renderScene();
}

let fontStyle = null;
let loader = new THREE.FontLoader(manager);
loader.load('https://threejs.org/examples/fonts/droid/droid_serif_bold.typeface.json', function(response) {
  fontStyle = response;
});

In the initialize() function:

function initialize(){
    // create scene, camera, and renderer instances
    ...
    function setCustomText(text, position) { // you can pass any parameters for the text here
        textGeometry = new THREE.TextGeometry(text, {
            font: fontStyle,...
    }
}

The key concept is to load all resources first before proceeding with other tasks.

More information on THREE.LoadingManager().

See the example on jsfiddle.

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

Understanding how to infer literal types or strings in Typescript is essential for maximizing the

Currently, my goal is to retrieve an object based on the parameter being passed in. I came across a similar question that almost meets my requirements. TypeScript function return type based on input parameter However, I want to enhance the function's ...

Unlock the Power of EmailJS with Vue.js 2 and TypeScript

I couldn't find a similar issue online, so here's my problem. I'm trying to create a form for receiving contact from an app using Vue.js 2 and TypeScript. Here is my code: <form ref="form" class="form-data" @submit.pr ...

transitioning from angular cli version 1.7 to version 12

Looking for a detailed guide on upgrading from version 1.7 to the latest Angular version (12/11)? I currently have an app running on version 1.7 and couldn't find a step-by-step process here: upgrading angular Would it be safe to assume that the upgr ...

Creating an object key using a passed literal argument in TypeScript

Can the following scenario be achieved? Given an argument, how can we identify the object key and access it? Any potential solutions? async function checkKey(arg:'key1'|'key2'){ // fetchResult returns an object with either {key1:&apo ...

Include form data into an array of objects within an Angular data source

I am struggling to add the edited form data from edit-customers-dialog.ts into an array of objects in my datasource. The form.data.value is returning correctly, but I'm facing issues with inserting it properly into the array. As a beginner in Angular ...

Modifying the text of a material UI button depending on a particular condition

I have a component that uses the Material UI button, and I need to change the text of the button based on a condition. If the order amount is 0, I want it to display "cancel", otherwise, it should show "refund". Can someone guide me on how to achieve thi ...

NestJS enforces HTTPS for Swagger redirects, whereas other endpoints are allowed to work on HTTP

I'm running into a strange problem with the Swagger interface on my NestJS server, which is hosted on a Windows Server environment and managed by PM2. While all other endpoints work fine over HTTP, the Swagger interface can only be accessed via HTTPS. ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

Upon reacting with Typescript, the window will transition to the homePage, however, it will also reset

Trying to redirect this component to the HomePage</code causes the data to restart once it reaches the home page.</p> <p>Any recommendations for an alternative to <code>window.location.href = "/HomePage"? import React, { useE ...

How come my ts-mockito spy isn't delegating method calls properly?

In my code, I have a class named MyPresenter which has a method called doOperation(). This method calls another method on a View class that implements an interface and is passed in as a parameter. Below you can find the implementation of the class, interfa ...

Angular2 and Typescript paired with Visual Studio 2013

Currently, I am utilizing the angular2 QUICKSTART and encountering an issue where Visual Studio fails to recognize Angular2 with typescript import Modules. However, everything else seems to be functioning correctly: https://i.stack.imgur.com/0s46Y.jpg Th ...

Error: The term "OrbitControls" is not recognized in the three

When attempting to import OrbitControls.js, I encounter the following issue: The error message Cannot use import statement outside a module is displayed. To resolve this, I add: <script type="module" src="OrbitControls.js">< ...

Can we create an alias for the import path in TypeScript?

import A = require('../../distant/PathToA'); import B = require('./different/path/PathToB'); I am utilizing external modules (commonJS) and browserify, with WebStorm as my editor. If this were just regular javascript, there are severa ...

How to Animate the Deletion of an Angular Component in Motion?

This stackblitz demonstration showcases an animation where clicking on Create success causes the components view to smoothly transition from opacity 0 to opacity 1 over a duration of 5 seconds. If we clear the container using this.container.clear(), the r ...

Mastering the art of debugging feathersjs with typescript on VS Code

I am facing an issue while trying to debug a TypeScript project with FeathersJS using VSCode. Whenever I try to launch the program, I encounter the following error: "Cannot start the program '[project_path]/src/index.ts' as the corresponding J ...

Urgent dependency alert: calling for a necessity (sequelize) in next.js is a vital element

I'm encountering a challenge with integrating sequelize into my Next.js 13 project to connect my API routes with the database. I keep receiving errors that say "Critical dependency: the request of a dependency is an expression." import * as pg from &a ...

Encountering an issue with TypeScript after applying a wrapper to a Material-UI button - specifically, the error message states that the type '{ children: string; color: "light-green"; }' is lacking certain properties

I'm currently working on creating wrapped components using MUI (@material-tailwind/react) within the environment of Next.js 14. However, I've run into a typescript error specifically in the MaterialButton component. Type '{ children: string; ...