html, body { margin: 0; padding: 0;}canvas { display: block;}
// first declare a global font variablelet font; async function setup() { createCanvas(windowWidth, windowHeight); // then load it font = await loadFont("/static/fonts/ABCAreal-Medium.ttf"); // then use it displayMessage();}// This runs continuously at every frame!async function draw() {}// Display a messagefunction displayMessage () { textSize(32); textAlign(CENTER); // then apply it textFont(font); fill('orangered'); text('Hello World', width/2, height/2);}
If you are not familiar with async and await keywords, please check out 12-async-await
Using Variable Fonts
We can use variable fonts in P5. A nice trick for this is creating a variable assigned to one of the font variable axis, typically the weight or slant.
Below, we created a w variable, and mapping the min-max values of variable axis (100–900) to the mouseX position (0->width).
This variable then was passed as parameter in our displayMessage() and displayWeightValue() functions.
html, body { margin: 0; padding: 0;}canvas { display: block;}
let font; async function setup() { createCanvas(windowWidth, windowHeight); font = await loadFont("/static/fonts/Inter-VariableFont_opsz,wght.ttf"); textFont(font);}async function draw() { background(0); // creating a variable for the weight // make it interactive with the mouse let w = map(mouseX, 0, width, 100, 900) displayWeightValue(w); displayMessage(w);}// Display Weight Valuefunction displayWeightValue(w) { textSize(16); textAlign(LEFT, TOP); fill('white'); textWeight(100); text("Move your mouse.\nWeight:" + w, 16, 16);}// Display a messagefunction displayMessage (w) { textSize(64); textWeight(w); textAlign(CENTER, CENTER); fill('orangered'); text('Hello World', width/2, height/2);}
3D Typography
Typography in 3D behaves a little differently: it must be converted into a 3D geometry, using the .textToModel() method to our loaded font.
An optional parameter object can be passed to allow for further customizations. For example, sampleFactor allows to set the quality of the geometry, or extrude allows to bring volume to our text block.