What is the process for adjusting the font size of a custom rendering on an off-screen canvas using three.js?

When it comes to using custom fonts and rendering them on an off-screen canvas, there is a common issue I've encountered. Even though I have managed to make it work, adjusting the size of the font rendering seems to be causing some trouble - resulting in a tiny display of the font.

Most resources I've come across, such as w3schools.com and developer.mozilla.org, typically assume that we are all using system fonts and provide a simplistic way of setting the font size by mixing it with the font name like this: ctx.font = "30px Arial";

However, here's the catch - when I try to use the name of my custom font file placed in the same folder ("custom.woff" or .otf), it works fine. But if I attempt to add the size in pixels or points like this ("30px custom.woff"), it simply does not work!

In addition, other font parameters such as font weight appear to be defined separately, which adds to the frustration. So, the question remains - is there a method to adjust the rendering size of a custom font for an off-screen canvas created in JS?

The process of creating the off-screen canvas involves:

var offScreenCanvas = document.createElement('canvas');
offScreenCanvas.width = 256;
offScreenCanvas.height = 256;
var ctx = offScreenCanvas.getContext("2d");

Subsequently, rendering the font looks something like this:

ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.font = 'custom.woff'; 
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, offScreenCanvas.width, 256);

ctx.fillStyle = 'black';
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(txt, offScreenCanvas.width / 2, offScreenCanvas.height / 2); 

Finally, I convert that rendering into a texture and utilize it on a three.js surface.

Version utilized: three.js r96.0

If you want to see how font substitution works on jsfiddle, refer to the comments section: https://i.sstatic.net/Qqkkx.png

Answer №1

To customize the font in CSS, you can define a font face rule with your preferred name and then reference it using that unique name.

<style>
@font-face {
    font-family: 'uniquefont';
    src: url('custom.woff');
}
</style>

After defining the font, you can use it in your script like this:

ctx.font = '30px uniquefont';

If you want to directly pass the font file for customization, you can also try this method:

ctx.font = "fontfile.woff";
// Make sure to wait for the font to load before adjusting its size
ctx.font = ctx.font.replace('(\d+)px', "20px");

Answer №2

My approach to creating off-screen canvas in JS involves generating textures from various font renderings on canvas without predefining it first in HTML. Utilizing custom fonts stored in a folder instead of loading Google fonts posed some challenges, but with the assistance of Gabriele Petrioli and Mugen87 from discourse.threejs.org, I managed to resolve them.

After fine-tuning my solution, I successfully tested it on Firefox, Chrome, and Opera. Since IE11 lacks support for three.js functionality, I opted not to focus on compatibility for that browser (and considering I'm still using Windows 7, I have little insight on how it performs on Edge).

Key insights include:

document.fonts.onloadingdone = function (fontFaceSetEvent) {

   // create canvas and render the font here (see above) 

}

Incorporating custom fonts positioned in a folder was crucial for my setup:

Embed this snippet inside style or CSS:

  @font-face {
    font-family: 'custom bold';
    src: url('fonts/custom bold.woff') format('woff');
  }
  @font-face {
    font-family: 'custom reg';
    src: url('fonts/custom regular.woff') format('woff');;
  }

To ensure compatibility with Chrome, defining the font-family within the body style was necessary. As I required multiple fonts, I implemented this in JS whenever a specific font was needed:

var fontreg;

fontreg = "custom reg";
document.body.style.fontFamily = fontreg;

ctx.font = "40px " + fontreg;

Hopefully, these insights prove beneficial to others facing similar challenges.

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

What is the method for exporting data directly from an EC2 instance to a file, such as a .txt or .json file?

I tried exporting the security group rules from EC2 into a file, like .txt or .json, using javascript/node.js. However, my attempts were unsuccessful. I wrote a code to retrieve information about security groups (rules, ingress, egress, etc.) and save it ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

Creating an HTML Form that Sends an Email

I'm completely stumped as to where the issue lies! The mail() function is working perfectly fine (I tested it with a simple PHP file), but for some reason, my form isn't sending any emails! HTML <section id="contact"> <div id="go ...

Is there a way to verify if a user has selected the correct answer in a quiz program?

Here we have code segments in ajax, javascript, html, and an xml file. I'm looking to calculate the total score based on user input to determine if they selected the correct answers for a test. I've attempted to figure this out, but I'm str ...

Retrieve data in JSON format from an external source file

I've been attempting to retrieve JSON content from an external file named list.json, but unfortunately all of my efforts have been unsuccessful. I've created a prototype of my code on Jsfiddle (http://jsfiddle.net/ctmvcyy1/). I believe that the ...

Adding multiple variables in jQuery: A guide to mimicking the .= operator from PHP

Being new to jQuery, I'm a bit unsure of how to achieve this. Typically in php, I can accomplish something like this: $result = ''; $result .= 'Hi'; $result .= ' there'; echo $result; I'm simply wondering if there ...

Leveraging the break and continue statements within the each() and forEach() functions

The functional style looping/mapping technique seems puzzling to me without the ability to use break and continue keywords. I find myself faced with this dilemma: collections.users.models.forEach(function(item, index) { //unable to implement break or ...

Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category con ...

Choosing multiple values in the selectize plugin from the controller: A step-by-step guide

Need help with selecting multiple options I'm utilizing the following plugin: https://github.com/selectize/selectize.js/blob/master/docs/usage.md I have an object as displayed in the image below: https://i.stack.imgur.com/sQsKe.png This is my Client ...

Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions? //a ...

Click on the button to insert a new row into the table

Recently I've begun learning Angular. In my project, there is a table and a button. When the button is clicked, a new row identical to the previous one should be added to the table. I have included a link to the StackBlitz demo below. Any guidance on ...

PHP Tutorial: Dynamically Adding or Removing Divs Based on Checkbox Selection

Check out this code snippet: <div id="product"> <b>SELECT PRODUCT:<br></b> <input type="checkbox" name="fruits" value="1">Orange<br> <input type="checkbox" name="fruits" value="2">Grapes<br> <input type=" ...

Mouseover function ceases to function once an element is dropped

After referencing this discussion, I successfully managed to drag items from one scroll overflow to another. However, the issue arises when these items (or their clones) are in the other scroll overflow as they do not respond to .mouseover(). The goal is ...

Having trouble with SQLite and local storage in Android PhoneGap app specifically on Samsung Galaxy devices

My PhoneGap app is running smoothly on iOS and most Android devices, but I'm encountering an issue specifically with Samsung Galaxy S3 and S4. Upon the initial page load, the app creates a local SQL database to store question and answer values. Howev ...

Arrange a collection of items based on a specific criterion, include the sorted position within each item, and revert back to the

Let's say we have the following array: const array = [ { name: 'b' }, { name: 'a' }, { name: 'c' }, ] The objective is to add a new property to each object based on its position in the sorted array: con ...

Tips for generating a JSON response for a signed-in user on a React application

I recently started experimenting with react and attempted to fetch the logged in user information, but unfortunately I encountered issues. In my Django view, I have set up a function to display the user data: def user_details_view(request, *args, **kwargs) ...

Transforming Lapton images into JPEG format on the fly

I have been working on a project where I am compressing jpeg images to .lep format. Now, I have created an .exe file that can convert the .lep image back to jpeg. My goal is to write a simple JSP script that can decode the .lep image on-the-fly and displ ...

BufferGeometry causing error for novice Tree.js users trying to implement functions

<script lang="ts"> import { onMount } from 'svelte'; import * as THREE from 'three'; var scene: THREE.Scene; var camera: THREE.Camera; var renderer: THREE.Renderer; let canvasElement: HTMLCanvasE ...

Troubleshooting problem with JSON object and HTML paragraph formatting

Attempting to incorporate my JSON object value into <p> tags has resulted in an unexpected change in formatting. The output in the console.log appears as shown in this image LINE INTERFACE UNIT,OMNITRON DX-64 LIU Item ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...