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 areFontFace
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 returnsundefined
. -
Example:
const customFont = fonts.get('CustomFont');if (customFont) {console.log('Font loaded:', customFont);}
Example Usage
// Create a Fonts instanceconst fonts = new Fonts();
// Load custom fontsfonts.load([ { name: 'CustomFont', path: './fonts/CustomFont.woff2' }, { name: 'AnotherFont', path: './fonts/AnotherFont.woff2' },]);
// Retrieve a font by nameconst customFont = fonts.get('CustomFont');if (customFont) { console.log('CustomFont is loaded and ready to use!');}
Notes
- The
load()
method uses theFontFace
API to load and register fonts with thedocument.fonts
property. - Fonts are stored internally in the
fonts
property and can be retrieved using theget()
method for further use.