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