nx.js
Concepts

Fonts

Built-in fonts and custom fonts for use with the Canvas API

When your application is using canvas rendering mode, nx.js offers a set of built-in fonts which are available for use in your application. You may also load custom fonts from font files.

Built-in fonts

nx.js comes with a set of built-in fonts which are available for use in your application.

FontDescription
"system-ui"The default font which is used by the Switch operating system.
"system-icons"A font which contains the icons used by the Switch operating system.

system-ui

The default font which is used by the Switch operating system. The Canvas API's default font sans-serif is also an alias for this font.

const ctx = screen.getContext('2d');
ctx.font = '48px system-ui';
ctx.fillStyle = 'white';
ctx.fillText('This is the "system-ui" font', 50, 300);

system-icons

The "system-icons" font contains icons used by the Switch operating system. When using this font, you will need to reference the correct unicode codepoint for the icon when invoking the fillText() function to render the icon glyphs.

const ctx = screen.getContext('2d');
ctx.font = '48px system-icons';
ctx.fillStyle = 'white';
ctx.fillText('\uE122', 50, 300);

Custom fonts

It is possible to load your own font files into an nx.js application, which involves a few steps:

  1. Create a FontFace instance
  2. Register the font with the FontFaceSet registry
  3. Use the font with the Canvas API

Loading a font

To load a font, you'll need to create an instance of the FontFace class, by providing the name of the font and the font data as an ArrayBuffer:

// Load the font data into a `FontFace` instance
const fontData = await Switch.readFile('romfs:/fonts/Arial.ttf');
const font = new FontFace('Arial', fontData);

The FreeType 2 library is used to renders fonts, so any font file format which is supported by FreeType 2 (typically .ttf or .otf) will work with nx.js.

Registering a font

Once you've loaded a font, you'll need to register it with the FontFaceSet registry. The fonts global is available for this purpose, similar to how you would register a font in a "web worker" context.

// Add the font to the global `fonts` registry
fonts.add(font);

The fonts registry is a global object that contains all the fonts that have been loaded into the application. You can use this registry to render text to the screen using the Canvas API.

Example

src/main.ts
const fontData = await Switch.readFile('romfs:/fonts/Arial.ttf');
const font = new FontFace('Arial', fontData);
fonts.add(font);
 
// Render to the screen using the Canvas API by setting the "font" property
const ctx = screen.getContext('2d');
ctx.font = '48px Arial';
ctx.fillStyle = 'cyan';
ctx.fillText('This is the "Arial" font', 50, 300);

On this page