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
Section titled “Constructor”new Fonts();Creates a new Fonts instance with an empty font collection.
- Returns:
A new
Fontsobject.
Properties
Section titled “Properties”fonts(Object): A collection of loaded fonts, where the keys are font names and the values areFontFaceobjects.
Methods
Section titled “Methods”load(fontDefinitions)
Section titled “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)
Section titled “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
FontFaceobject 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
Section titled “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!');}- The
load()method uses theFontFaceAPI to load and register fonts with thedocument.fontsproperty. - Fonts are stored internally in the
fontsproperty and can be retrieved using theget()method for further use.