Reference loadFont()

loadFont()

Loads a font and creates a p5.Font object. loadFont() can load fonts in either .otf or .ttf format. Loaded fonts can be used to style text on the canvas and in HTML elements.

The first parameter, path, is the path to a font file. Paths to local files should be relative. For example, '/assets/inconsolata.otf'. The Inconsolata font used in the following examples can be downloaded for free here. Paths to remote files should be URLs. For example, 'https://example.com/inconsolata.otf'. URLs may be blocked due to browser security.

In 2D mode, path can take on a few other forms. It could be a path to a CSS file, such as one from Google Fonts. It could also be a string with a CSS @font-face declaration. It can also be an object containing key-value pairs with properties that you would find in an @font-face block.

The second parameter, successCallback, is optional. If a function is passed, it will be called once the font has loaded. The callback function may use the new p5.Font object if needed.

The third parameter, failureCallback, is also optional. If a function is passed, it will be called if the font fails to load. The callback function may use the error Event object if needed.

Fonts can take time to load. await the result of loadFont() in setup() before using the result.

Examples

Syntax

loadFont(path, [name], [successCallback], [failureCallback])
loadFont(path, [successCallback], [failureCallback])

Parameters

path
String|Object: path of the font to be loaded, a CSS @font-face string, or an object with font face properties.
name
String: An alias that can be used for this font in textFont(). Defaults to the name in the font's metadata.
successCallback
Function: function called with the p5.Font object after it loads.
failureCallback
Function: function called with the error Event object if the font fails to load.

Returns

Promise<p5.Font>: p5.Font object.
Notice any errors or typos? Please let us know. Please feel free to edit src/type/p5.Font.js and open a pull request!

Related References