preload()
preload() is special in p5.js—it runs before setup(), ensuring that slow resources like fonts and images are fully loaded before drawing begins. The URL pattern shows how to load fonts from Fontsource's free library.
function preload() {
// Load the Roboto font from Fontsource CDN
// Convert font name to slug: "Roboto" -> "roboto"
// URL pattern: https://unpkg.com/@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');- Loads a custom Roboto font from a CDN (content delivery network) and stores it in the myFont variable so it's ready before setup() runs