Creating dynamic animations with three.js using the fontLoader() function

While attempting to deploy my website, I encountered a bug where the three.js canvas failed to load (even though it worked fine in development). The issue arises when trying to animate text loaded using fontLoader.load(). For instance, adding text to the scene as shown below:

fontLoader.load(
  'node_modules/three/examples/fonts/droid/droid_serif_regular.typeface.json',
  (droidFont) => {
    const textGeometry = new TextGeometry('Scroll to Start', {
      size: 5,
      height: 1,
      font: droidFont,
      bevelSize: 5,
      bevelThickness: 2,
    
    });
    const introTexture = new THREE.TextureLoader().load('suntexture.png');
    const textMaterial = new THREE.MeshBasicMaterial({map: introTexture, transparent:true, opacity: .5});
    cosnt introText = new THREE.Mesh(textGeometry, textMaterial);
    introText.position.set(-5, 37, -140);
    scene.add(introText);
  }
);

To achieve a soft oscillating effect on the text, I would typically include this snippet in my animation function called at the end of main.js:

function introAnimate() {
    introText.position.y += (Math.sin(clock.getElapsedTime())/62.8);
    introText.rotation.y += (Math.cos(clock.getElapsedTime())/700);
}

The issue lies in the console mentioning that introText is not defined (presumably due to its declaration within a function). Attempts to resolve this by declaring them as var or const and prepending with globalThis. or window. did not yield any results.

Surprisingly, the npm run dev version ran without errors despite this reference issue.

Although flow offers some text animation solutions using three.js, I am specifically interested in triggering animations based on scrolling behavior and dynamically altering properties that flow may not support. Any advice on how to address this would be greatly appreciated.

Answer №1

It appears that the issue you're facing is due to executing introAnimate() before your font has completed loading.

fontLoader.load() operates asynchronously, which means it begins loading while the rest of your code (such as introAnimate()) continues to run until the font finishes loading and triggers the callback.

While the font may load quickly in your local or development environment, it can take longer to download in a production setting.

If introAnimate() attempts to execute before the callback initializes window.introText, it will encounter an error.

To resolve this issue, consider initializing window.introText = null before calling fontLoader.load(), updating it once it's ready, and checking for its existence within your introAnimate():

function introAnimate() {
    if (introText === null) return;

    introText.position.y += (Math.sin(clock.getElapsedTime())/62.8);
    introText.rotation.y += (Math.cos(clock.getElapsedTime())/700);
}

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

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

What is the best way to define the entry points for all files in tsup/typescript that compile into the root dist

In my TypeScript project, I am utilizing the tsup build tool for bundling. I have a requirement to specify all the folders and files within the components directory to the root dist folder. src/ components/ card/ card.tsx ...

Creating a TypeScript module declaration for exporting a class

Just starting out with TypeScript and running into issues while trying to load an es6 javascript module. Here's the code snippet from my javascript file: //TemplateFactory.js export class TemplateFactory{ static getTemplate(module){ } } In ...

JavaScript creates dynamic three.js animations on top of an image

When you visit the link above, you will see an animation of stars and a sphere reflecting that animation. My goal is to have https://i.sstatic.net/VpxWH.png It would mean that the reflective sphere is displayed on the astronaut's helmet. I am strug ...

Managing variables or properties that are not defined in ES6

Currently, I am utilizing Angular and Firebase Firestore in my project. However, the question posed could be relevant to Typescript and pure Javascript as well. The functionality of my application relies heavily on the data retrieved from Firestore. A sim ...

Tips for smoothly applying a class to an image for seamless transitions, avoiding any awkward clunkiness

Check out my work on jsfiddle I understand that the image may not be visible, but I'll do my best to describe it. The header smoothly animates as I scroll down, but the image abruptly changes size instead of smoothly resizing. I want it to gradually ...

Sending information to functions through input

I am facing a challenge with an input field setup like this: <input type="text" @input=readInput('usernameInput')> Accompanied by data and methods for handling it: data() { return { usernameInput = false; }; }, readInput(for ...

Leveraging the power of JavaScript templates within ASP.NET

Throughout my career, I have encountered a recurring issue that has yet to be resolved with an elegant solution. Picture this: You have a basic page with a repeater that is populated on the server side through data binding. Everything works smoothly and ef ...

Is there a way to ensure the content of two divs remains aligned despite changing data within them?

Currently, I have two separate Divs - one displaying temperature data and the other showing humidity levels. <div class="weatherwrap"> <div class="tempwrap" title="Current Temperature"> ...

Merge two JSON arrays without specifying which fields to combine explicitly

After converting two Excel sheets to JSON using an online tool, two separate JSON properties were created for each sheet. The resulting JSON example looks like this: { "Product Info": [ { // Product information details here }, ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

Is there a way to identify when Change Detection has been triggered in Angular2 without using @Output directly?

Imagine the following structure of components in Angular2 A B D E When D triggers an event by clicking on B, Angular2 will automatically initiate change detection starting from the root component A. But is there a method to log this change detect ...

Creating a table and populating its cells with values all within the confines of a single function

This section of code aims to create 3 arrays by extracting values inputted by the user from a popup menu in the HTML file. These values are then utilized to populate the table displayed below. var arrM = new Array; var arrT = new Array; var ar ...

Is there a way to conceal the parent div when all of its child divs are hidden?

I have a series of dynamically created divs set up like this: <div class='parent'> <div class='child'></div> <div class='child'></div> <div class='child'></div> < ...

How can I make a page scroll to the center when clicking on a carousel?

My goal is to create a webpage where clicking on the carousel will center it on the page. A great example of this functionality can be seen on the Studio New Work website (). As I am still in the process of learning JQuery, I have not yet mastered all the ...

Executing a click on a checkbox element in Python with Selenium

Background: Currently, I am in the process of developing a Python script that will automatically download listings from a specific website. I have successfully programmed the script to navigate the webpage, search for keywords, click on the search button, ...

What is the proper way to display the date and time 2021-11-14T18:30:00.000+00:00?

Here is my ts file code: mydate: Date = new Date('2021-11-14T18:30:00.000+00:00'); However, I want the date to be in this format:- 07-July-2022 If anyone can assist with achieving this format, it would be greatly appreciated. Thank you! ...

Why is the Express validator failing to work with the posted value?

I have come across an issue with my current code. Everything is working fine, but I need to access req.body.type in the createValidationFor function. However, when I try to access it, the validation stops working and I can't figure out why. router.po ...

Including an additional row in a pre-existing table

My goal is to dynamically add a new row when a button is clicked, right after the row containing the button. To achieve this, I'm using jQuery (version 1.10.2) to handle the creation of new rows. The issue I'm facing is related to the behavior o ...

Tips for halting click propagation in VueJS

My dilemma lies within a recursive list (tree) where each element contains a @click="sayHello(el.id)". The challenge arises due to the nested structure of the list, such as: list-element-0-01 ├──list-el-1-01 │ └──list-el-2-01 └──list ...