Properties of MakeTextSprite in THREE.JS

Utilizing the function "MakeTextSprite" from

function createTextSprite(message, parameters) {
        if (parameters === undefined) parameters = {};
        var fontface = parameters.hasOwnProperty("fontface") ? parameters["fontface"] : "Helvetica";
        var fontsize = parameters.hasOwnProperty("fontsize") ? parameters["fontsize"] : 18;
        var borderThickness = parameters.hasOwnProperty("borderThickness") ? parameters["borderThickness"] : 0;
        var borderColor = parameters.hasOwnProperty("borderColor") ? parameters["borderColor"] : {
            r: 0,
            g: 0,
            b: 0,
            a: 1.0
        };
        var backgroundColor = parameters.hasOwnProperty("backgroundColor") ? parameters["backgroundColor"] : {
            r: 255,
            g: 255,
            b: 255,
            a: 1.0
        };
        var textColor = parameters.hasOwnProperty("textColor") ? parameters["textColor"] : {
            r: 0,
            g: 0,
            b: 0,
            a: 1.0
        };

        var canvas = document.createElement('canvas');
        var WIDTH = 400;
        var HEIGHT = 150;

        canvas.width = WIDTH;
        canvas.height = HEIGHT;
        var context = canvas.getContext("2d", {alpha:false});
        context.font = fontsize + "px " + fontface;

        var metrics = context.measureText(message);
        var textWidth = (metrics.width);

        context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + "," + backgroundColor.a + ")";
        context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + "," + borderColor.b + "," + borderColor.a + ")";

        context.lineWidth = borderThickness;
        roundRect(context, borderThickness / 2, borderThickness / 2, (textWidth + borderThickness) * 1.1, fontsize * 1.4 + borderThickness, 8);

        context.fillStyle = "rgba(" + textColor.r + ", " + textColor.g + ", " + textColor.b + ", 1.0)";
        context.fillText(message, borderThickness, fontsize + borderThickness);
        var texture = new THREE.Texture(canvas, THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping, THREE.NearestFilter, THREE.NearestFilter);
        texture.needsUpdate = true;
        var spriteMaterial = new THREE.SpriteMaterial({
            map: texture,
            useScreenCoordinates: false,
            transparent: false,
        });
        var sprite = new THREE.Sprite(spriteMaterial);
        sprite.scale.set(30, 15, 0);
        return sprite;
    }
    enter code here

I instantiated my Sprite using this method:

  Array[i] = createTextSprite(Array[i].name, {
                fontsize: 100,
                borderColor: {
                    r: 255,
                    g: 255,
                    b: 255,
                    a: 1.0
                },
                backgroundColor: {
                    r: 255,
                    g: 255,
                    b: 255,
                    a: 1
                }
            });

I wanted to modify the Width property. Setting it to 1000 caused the canvas to shrink in SpriteMaterial. Thus, the size of my Sprite remains constant.

Furthermore, the font appears pixelated and I have been unsuccessful in trying to smooth the font.

Answer №1

Adjust the width of your image sprite by increasing the textWidth variable.

var metrics = context.measureText(message);
var extend = 1000;
var textWidth = (metrics.width) + extend;

This modified width will be used in the roundRect(...) function to draw the sprite.

To fix any distortion, resize the sprite proportionally:

var width = spriteMaterial.map.image.width;
var height = spriteMaterial.map.image.height;

sprite.scale.set( width/10, height/10, 1 );

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

Absence of shadow casting in ThreeJS within react-three-renderer

I'm struggling to get a shadow to show up in my scene. Here are the steps I've already taken: Added the shadowMapEnabled attribute to the React3 element Configured the directional light in my scene exactly like the example in this repository En ...

Creating a video that plays frame-by-frame on an HTML5 canvas and can be controlled with a slider

I am currently working on a walkthrough video where the user has the ability to slide a UI slider across the screen, causing the camera to navigate through a 3D space. The video itself has been exported in jpg frames, numbered from 0 to 350.jpg. My appro ...

Upload an image to a Node.js API using the Next.js API directory

I am working with a file instance that I obtained from the formidable library. Here's how it looks: photo: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 16648, path: 'public/ ...

What is the best way to delete table rows based on their assigned class?

Within my HTML document, there is the following structure: <table id="registerTable"> <tr class="leaderRegistration"> <!--table contents--> </tr> <tr class="leaderRegistration"> <!--table conten ...

Replacing default hover behavior from an external library

Currently, I am utilizing a JS library that comes with a specific widget. Basically, I have the following list (I removed unnecessary DOM code): <li class="disabled"> When I hover over this list item, it turns into: <li class="disabled state-a ...

Specific Character Count in Regular Expressions

THIS IS DISTINCT FROM THE REFERENCED QUESTION because I have extensively researched and tested various solutions before resorting to posting this inquiry. I am in need of a validation for inputs that adhere to the following criteria: The first character ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

What is the best way to handle returning a promise when outside of the scope?

I am currently working on retrieving multiple files asynchronously from AWS S3 by utilizing Promises in my code. Although I'm using AWS S3 for fetching the files, there seems to be an issue with fulfilling the promises as it's out of scope and c ...

Testing the unit with a customized header in the interceptor

I've been struggling to execute a unit test within an Angular 6 interceptor, but despite numerous attempts, I keep encountering the following error: Error: Expected one matching request for criteria "Match by function: ", found none. I'm rela ...

Adding HTML created by PHP to a document fragment

I am trying to add a large amount of HTML generated by PHP (5000 div elements) to a document fragment and then append it to the body of the page. Here is an example of the HTML: <div itemscope itemtype="http://schema.org/Article"> <link itemprop ...

What could be causing my images not to show up when I use string interpolation for src links in Vue.js?

I've encountered an issue while working on Vue.js where I'm struggling to render a couple of images from the local directory. What puzzles me is that this problem arises when using string interpolation, like in the code snippet below: <img :s ...

A guide on dynamically checking the checkbox values in each row of a table using JavaScript or jQuery

My table is dynamically populated with values from a database using the following code: var row = table.insertRow(i); i = i+1; // Insert new cells (<td> elements) at the 1st and 2nd position of the new <tr> element: var cell1 = row.insertCell ...

The behavior of JS Array.push may catch you off guard

There seems to be an issue with the push function in my code. The problem lies in the last line of code shown below. export enum non_searchFieldsNames { language = 'language', categories = 'categories', subtitle = 'subt ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

Customizing the step function of HTML5 input number with jQuery: A guide

Is there a way to modify the step value in HTML5 number inputs for my web application? I would like it to increment and decrement by 100 instead of 1. I attempted the following approach: $("#mynumberinput").keydown(function(e){ if (e.keyCode == 38) / ...

Is the node certificate store limited to reading only from a predefined list of certificates?

Is there a way to add a new certificate to the list of certificates node trusts, even after some struggle? It appears that Node only trusts certificates hardcoded in its list located here: https://github.com/nodejs/node/blob/master/src/node_root_certs.h ...

What is the best method for handling and analyzing error objects within a catch statement following an API request?

When working with an API, dealing with complex error objects is a common occurrence. https://i.sstatic.net/0iK9t.png Depending on the specific API, the error messages can be quite informative and sometimes you may want to directly display them to the use ...

Why is the JavaScript function loaded through Ajax not running as expected?

I manage several websites with identical data protection policies. To streamline the process, I've created a file on a separate server that can be accessed through Ajax integration. One crucial aspect is the ability to set an opt-out option and store ...

Learn how to effortlessly integrate and utilize a bpmn file in a Vue component by leveraging the raw-loader

As a newcomer to bpmn-js, I am facing the challenge of importing and utilizing a .bpmn file within a vue.js component (BPMNViewer.vue). Despite my efforts in researching, I could only find recommendations to use the raw-loader. Consequently, I am currently ...

AngularJS encountered an error: The token '|' was unexpected and expected ':' instead

My HTML file contains a condition where certain fields need to be displayed automatically in landscape mode using filters. However, when I run the program, I encounter the following code: <tbody> <tr ng-repeat="ledger in vm.ledgers ...