Memory problem with rendering text on a 2D canvas in ThreeJs

How can I optimize my code for rendering nearly 200 texts using 2D canvas rendering? The current method is consuming a lot of memory. Is there a way to reuse the canvas element? Here is a snippet of my current implementation:

var goalCanvas = document.createElement('canvas');
goalCanvas.width = Math.pow(2, Math.round(Math.log(parseInt(name.length) * parseInt(58)) / Math.log(2)));
goalCanvas.height = 128;
var planeGeometry = new THREE.PlaneGeometry(parseInt(name.length) * parseInt(3), 8);
var featureContext = goalCanvas.getContext('2d');
featureContext.fillStyle = "#ffffff";
featureContext.font = "54px roboto_condensedregular";
featureContext.textAlign = "center";
featureContext.fillText(name, goalCanvas.width / 2, 42);
var goalTexture = new THREE.Texture(goalCanvas)
goalTexture.needsUpdate = true;
var goalMaterial = new THREE.MeshBasicMaterial({
    map: goalTexture
});
goalMaterial.transparent = true;
var goalNameMesh = new THREE.Mesh(
    planeGeometry,
    goalMaterial
);

Answer №1

It is crucial to ensure that the creation of a new canvas occurs only once, executing the code that specifically adds text:

var planeGeometry = new THREE.PlaneGeometry(parseInt(name.length) * parseInt(3), 8);
goalCanvas.height = 128;
var featureContext = goalCanvas.getContext('2d');
featureContext.fillStyle = "#ffffff";
featureContext.font = "54px roboto_condensedregular";
featureContext.textAlign = "center";
featureContext.fillText(name, goalCanvas.width / 2, 42);
var goalTexture = new THREE.Texture(goalCanvas)
goalTexture.needsUpdate = true;
var goalMaterial = new THREE.MeshBasicMaterial({
    map: goalTexture
});
goalMaterial.transparent = true;
var goalNameMesh = new THREE.Mesh(
    planeGeometry,
    goalMaterial
);

If you intend to utilize this within a function, it should adhere to the following structure:

function AddText(canvas,name)
{
    var planeGeometry = new THREE.PlaneGeometry(parseInt(name.length) * parseInt(3), 8);
    var featureContext = canvas.getContext('2d');
    featureContext.fillStyle = "#ffffff";
    featureContext.font = "54px roboto_condensedregular";
    featureContext.textAlign = "center";
    featureContext.fillText(name, canvas.width / 2, 42);
    var goalTexture = new THREE.Texture(canvas)
    goalTexture.needsUpdate = true;
    var goalMaterial = new THREE.MeshBasicMaterial({
        map: goalTexture
    });
    goalMaterial.transparent = true;
    var goalNameMesh = new THREE.Mesh(
        planeGeometry,
        goalMaterial
    );
    return {"goalNameMesh": goalNameMesh, "goalTexture": goalTexture, "goalMaterial":goalMaterial, "featureContext": featureContext};
}


var goalCanvas = document.createElement('canvas'); //this should only run once
goalCanvas.width = Math.pow(2, Math.round(Math.log(parseInt(name.length) * parseInt(58)) / Math.log(2));//and this
goalCanvas.height = 128;//and this
var addedText = AddText(goalCanvas, name) //you can loop this line for each text that you want to add, and it will return an object with all the handles in it

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

Manipulate your table data with jQuery: add, update, delete, and display information with ease

When adding data dynamically to the table and attempting to edit, the checkbox value is not updating. This issue needs to be resolved. You can view the code in action on jsFiddle here on JSFiddle ...

Semantic UI (React): Transforming vertical menu into horizontal layout for mobile responsiveness

I have implemented a vertical menu using Semantic UI React. Here is the structure of my menu: <Grid> <Grid.Column mobile={16} tablet={5} computer={5}> <div className='ui secondary pointing menu vertical compact inherit&apos ...

Substitute Ajax.ActionLink with a different method

Hey there, I have an Ajax Action Link set up that is working perfectly fine. It displays some text from a partial view when the link is clicked. However, I want this text to be shown automatically when the page loads, without the need to click on the actio ...

Looking to incorporate AAD calling functionality in a React and Node application by utilizing the Graph API for communication/calls

As a newcomer to Microsoft Azure and its services, I recently registered an application with Azure. However, when attempting to integrate a call feature in my Web App using the graph API '/communication/calls', I encountered the following error m ...

Changing states in next.js is not accomplished by using setState

Struggling to update the page number using setCurrentPage(page) - clicking the button doesn't trigger any state change. Tried various methods without success. Manually modified the number in useState(1) and confirmed that the page did switch. import ...

Transmit blob information to node server using fetch, multer, and express

Currently facing an issue with sending a blob object to my node server. The scenario is that on the client side, I am recording some audio using MediaRecorder and then attempting to transmit the file to my server for further processing. saveButton.o ...

Do not proceed with the form submission if the fields are left blank

I am facing a challenge with organizing two sets of data, "heat" and "cold", obtained from an external provider. The data is messy and I have trimmed down the code to focus on the main issue at hand. Both "heat" and "cold" have properties that users need t ...

Utilizing JavaScript/AJAX JSON encoding for arrays: Tips for effectively utilizing the received data

I am trying to retrieve all the images from a specific folder on the server using an AJAX call. files = glob('assets/img/daily/*'); // obtain all file names $imageArr; foreach ($files as $file) { $imageArr[] = $file; } $jsonObj = json_encode ...

What is the best way to incorporate a rectangle or arrow into my canvas design?

Looking for a way to enhance my html canvas wind direction code, here is how it currently looks: var x, y, r, ctx, radians; ctx = window.compass.getContext("2d"); radians = 0.0174533 * (10 - 90); x = ctx.canvas.width / 2; y = ctx.canvas.height / ...

What is the reason for the React component being rendered four times?

My React component is fetching data from Firestore and storing it in the items array. However, I am encountering an issue where the menus variable contains three empty arrays that are being rendered on the page. Initially, I used an async function to fetc ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

Display the hover effect for the current card when the mouse is over it

When the mouse hovers over a card, I want only that specific card to show a hover effect. Currently, when I hover over any card, all of them show the hover effect. Is there a way to achieve this in Vue Nuxtjs? Here's what I am trying to accomplish: ...

How can I simulate the enter key being pressed for testing purposes using jQuery or pure JavaScript?

Is there a better method for simulating the user pressing the "Enter" key? I have tried using $(element).keypress() but it doesn't seem to capture the exact key pressed. This is specifically for unit testing purposes. ...

Switch the content of a textbox by clicking on a hyperlink within a jQuery div that updates dynamically

In my HTML code, I have a specific requirement: when a user clicks on <img src="https://www.fast2sms.com/panel/img/icons/add1.png" class="add-img">, the textbox should dynamically populate with the value 123456789 (with a different value for each < ...

Is there a way to identify when a radio button's value has changed without having to submit the form again?

Within this form, I have 2 radio buttons: <form action='' method='post' onsubmit='return checkForm(this, event)'> <input type = 'radio' name='allow' value='allow' checked>Allow ...

Supply mandatory argument along with varying arguments to the function

I have a function that requires one parameter and a dynamic set of additional parameters. I am passing an array of blobs to the function. Below is a simplified version of the function: function test(directory, blob0, blob1) { for (var argumentIndex = 1; ...

ReactJS has the capability to showcase two components simultaneously

I'm facing an issue with my ReactJS workspace where I have two components but only one is displaying. import React, { Component } from 'react'; import logo, { ReactComponent } from './logo.svg'; import './App.css'; impor ...

Odd spacing issue with Bootstrap's 'form-floating' label within a 'row' element

When using the form-floating class to achieve a floating label look, I encountered an issue with margins being disrupted when placing the class inside a row. For reference, here is how it looks without the row (label appears correctly): <link href ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

Locate the iframe that invoked a function within its parent element

There are multiple iframes on a page that showcase ads unicorns and bacon to users. Due to the impossibility of detecting an iframe's domready event from the parent (please correct me if I'm wrong), each iframe contains initialization code like t ...