The animation freezes when trying to create geometry and mesh using Three.js

I'm currently working on developing a text animation that scrolls and dynamically adds more content as it runs.

Here is the function I have created for generating the text geometry and mesh:

function createText(){
  textGeo = new THREE.TextGeometry( "Insert long, new text here", {
    size: 20,
    height: height,
    font: font
  });

  textMesh1 = new THREE.Mesh( textGeo, new THREE.MeshBasicMaterial( { color: 0x112358 } ) );

  textMesh1.position.x = (window.innerWidth / 2) + 100;
  textMesh1.position.y = ((window.innerHeight / 2) * -1) + 40;
  textMesh1.position.z = 0;

  textMesh1.rotation.x = 0;
  textMesh1.rotation.y = 0;

  group.add( textMesh1 );
}

Below is the animate function I am using:

function animate() {

    var firstBox = new THREE.Box3();

    requestAnimationFrame( animate );


    for(i = 0; i < group.children.length; i++){
      group.children[i].position.x -= 2;
    }

    firstBox.setFromObject(group.children[0]);

    if(group.children[0].position.x < ((window.innerWidth / 2) * -1) - firstBox.size().x ){
      scene.remove( group.children[0] );
    }

    render();

  }

Essentially, this animation scrolls through all the children of the group and removes them once they exit the screen.

The issue arises when I call the function to generate the text geometry and mesh (even without adding it to the group), causing the scroll animation to freeze briefly.

I've explored Web Workers as a potential solution to separate the creation process from the animation itself. However, since Web Workers cannot return the mesh object, this method doesn't address the problem effectively.

If anyone has suggestions on how to create the text geometry and mesh seamlessly without impacting the animation, I would greatly appreciate it! Thank you in advance!

Answer №1

To optimize your text rendering, consider breaking it down into smaller segments (such as individual words or even letters) and spreading out the generation of word meshes over multiple frames. One approach could be:

function TextSplitter( text, options, container ) {
    this.words = text.split( /\s/g );
    this.index = 0;
    this.process = function () {
        if ( this.index >= this.words.length ) return;

        var currentWord = this.words[ this.index ];
        ++this.index;
        var geometry = new THREE.TextGeometry( currentWord, options );
        var mesh = new THREE.Mesh( geometry, options.material );
        // Adjust the position of the mesh based on word length here
        container.add( mesh );
    }
}

Instantiate a TextSplitter object and invoke textSplitter.process() during the animation loop. The challenge may lie in positioning the text correctly, especially if the font is not monospaced. If that's the case, you may need to explore FontUtils for insights on spacing implementation and adapt it to the TextSplitter component.

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

extracting both the value and ID attributes from a RadioButtonGroup component in React MaterialUI

I am currently working on extracting the selected value and gameID from a dynamic MaterialUI RadioButtonGroup. Although I have been successful in retrieving the gameID, I am encountering difficulty in obtaining the value: <form onSubmit={this.handl ...

What could be causing this addEventListener to fail when I am assigning elements to a class?

I've encountered an issue with my code where I have two text inputs and two date inputs. I tried to select all of them using QuerySelectorAll with a class, added a click listener that should change the textContent of a div element to "", but it's ...

Exploring the .map() Method in ReactJS

Would it be feasible to integrate another Postgres database table into the current mapping displayed in this code? It would be ideal if it could be done using some sort of array function. {items.map(item => ( <tr key={item.id}& ...

Creating a custom calculator using Javascript

As a beginner in Javascript, I am seeking assistance in creating a simple calculator that can add numbers as buttons are clicked and display the running total. For example: If I click the button "20," it should display the number 20. Then, if I click the ...

What is the best way to implement CSS in this JavaScript Fetch code in order to manipulate the text's position and font style

Hello, I am just starting out with JS. Is there a way for me to customize the position and font of text in this JS Fetch function using CSS? Any help will be greatly appreciated. let file = 'art.txt'; const handleFetch = () => { fe ...

Deciphering the significance of matrices within a Three.js 3D object

Exploring the source code of THREE.Object3D reveals three key properties: matrix, matrixWorld, and matrixRotationWorld. Upon closer inspection, it appears that the object's position, scale, and rotation data can be extracted from the matrix. Furtherm ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Error: The term 'RequestCompleted' is not recognized by Microsoft JScript

Does anyone have any suggestions? The error above occurs when this code is executed: Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RequestCompleted); Specifically within this section: <script language="javascript" type="text/javas ...

What could be causing NestJS/TypeORM to remove the attribute passed in during save operation?

Embarking on my Nest JS journey, I set up my first project to familiarize myself with it. Despite successfully working with the Organization entity, I encountered a roadblock when trying to create a User - organizationId IS NULL and cannot be saved. Here ...

Incapable of modifying the inner content of a table

I am completely new to AngularJS and struggling with updating the inner HTML of a table. I have a variable that contains a string with three types of tags: strong, which works fine, and nested tr and td tags. However, when I try to replace the table's ...

How can JavaScript be used to dynamically load a second advertisement image immediately after the first ad image is successfully loaded?

Currently, I am working on ensuring that the 2nd ad image loads ONLY AFTER the 1st ad image has been loaded (please refer to the image with blue boxes). This is crucial as I have a CSS animation transitioning smoothly from the 1st ad image to the 2nd ad im ...

When trying to link a Redis microservice with NestJS, the application becomes unresponsive

I am attempting to create a basic hybrid app following the guidance provided by Nest's documentation, but I have run into an issue where the app becomes unresponsive without any errors being thrown. main.ts import { NestFactory } from '@nestjs/c ...

Ways to utilize array reduce for organizing information

Can someone please guide me on how to use the reduce array method to sort entries by date in the following data: const entries = [ {date: 'lu'}, {date: 'lu'}, {date: 'ma'}, {date: 'ma'} ] I would like the ou ...

Organizing content by title or link using jQuery

I am attempting to organize a list based on the title of a link so that it is displayed in an A-Z format. Unfortunately, I am unable to modify the HTML structure easily for better styling as I am restricted to using tr>tr>tr>. I am struggling to f ...

Change to JSONArray using angularjs

Here is a json object: "values": [ {"name": "name1"}, {"name": "name2"}, {"name": "name3"} ] I want to convert it into this format: values: ["name1", "name2", "name3"]; Can this conversion be done in AngularJS or any other JavaScript functi ...

Angular 1.5.0 - What is the reason for factory being invoked only once?

I am facing an issue with my html template where the data from an Angular factory is only loaded once when the page initially loads. Subsequent page openings show the same results from the first backend call, indicating a potential caching issue within the ...

Tips for accessing the current state/value in a third-party event handler?

Consider the following scenario: function MapControl() { const [countries, setCountries] = useContext(CountriesContext) useEffect( () => { ThirdPartyApi.OnSelectCountry((country) => { setCountries([...countries, country]) }) }) ...

What is the process for inserting HTML content into the body of an iframe?

Is there a way to insert HTML content into the body of an iframe instead of using the src attribute to call a page's URL? I am looking for a code that is compatible with all browsers and works perfectly. ...

Ways to conceal a child div element without using any specific ID reference

I encountered an issue where I need to conceal all divs within a parent div except the first one. The challenge is that these divs do not possess any unique identifiers. Is there a way to achieve this task using CSS or pure JavaScript? <div role="list ...

Exploring the world of jQuery animation and background colors with Animate()

I'm currently attempting to implement a basic pulse effect by utilizing JQuery to modify the background color. However, I am facing issues with animating the backgroundColor property. function show_user(dnid) { /* dnid represents the HTML ID of a ...