preload()
preload() runs before setup() and pauses the sketch until everything inside it (fonts, images, sounds) finishes loading. This guarantees myFont is ready by the time textFont(myFont) is called in setup().
function preload() {
// Load a custom font from Fontsource CDN.
// We're using Roboto regular (400 weight).
// The URL pattern is @fontsource/{slug}@latest/files/{slug}-latin-400-normal.woff
myFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');
}
Line-by-line explanation (1 lines)
myFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');- Downloads the Roboto font file from a CDN and stores the loaded font object in the global myFont variable, so it's ready to use before setup() runs.