Skip to content

Fonts

The Fonts class is responsible for loading and managing custom fonts within a web application. It provides functionality to load fonts from external sources and retrieve them for use in the document.

Constructor

new Fonts();

Creates a new Fonts instance with an empty font collection.

  • Returns: A new Fonts object.

Properties

  • fonts (Object): A collection of loaded fonts, where the keys are font names and the values are FontFace objects.

Methods

load(fontDefinitions)

load(fontDefinitions);

Loads custom fonts into the document based on an array of font definitions. Each font definition should specify the font’s name and path.

  • Parameters:

    • fontDefinitions (Array): An array of objects, each representing a font to load. Each object should have the following properties:
      • name (String): The name of the font.
      • path (String): The URL or path to the font file.
  • Returns: void

  • Example:

    const fonts = new Fonts();
    fonts.load([
    { name: 'CustomFont', path: './fonts/CustomFont.woff2' },
    { name: 'AnotherFont', path: './fonts/AnotherFont.woff2' },
    ]);

get(name)

get(name);

Retrieves a FontFace object by its name. This method allows access to a font that was previously loaded with the load() method.

  • Parameters:

    • name (String): The name of the font to retrieve.
  • Returns: A FontFace object corresponding to the specified font name. If the font has not been loaded, it returns undefined.

  • Example:

    const customFont = fonts.get('CustomFont');
    if (customFont) {
    console.log('Font loaded:', customFont);
    }

Example Usage

// Create a Fonts instance
const fonts = new Fonts();
// Load custom fonts
fonts.load([
{ name: 'CustomFont', path: './fonts/CustomFont.woff2' },
{ name: 'AnotherFont', path: './fonts/AnotherFont.woff2' },
]);
// Retrieve a font by name
const customFont = fonts.get('CustomFont');
if (customFont) {
console.log('CustomFont is loaded and ready to use!');
}

Notes

  • The load() method uses the FontFace API to load and register fonts with the document.fonts property.
  • Fonts are stored internally in the fonts property and can be retrieved using the get() method for further use.