preload()
preload() is a special function that runs once before setup(). Use it to load images, fonts, and other assets from the internet. Without preload(), your sketch would start before files finish downloading, causing errors.
function preload() {
// Load Earth texture from a reliable CDN
// Using the specific r147 tag for reliable access on raw.githubusercontent.com
earthTexture = loadImage('https://raw.githubusercontent.com/mrdoob/three.js/r147/examples/textures/planets/earth_atmos_2048.jpg');
// Load a font for WEBGL text from fontsource CDN (unpkg.com is reliable)
webglFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');
}
Line-by-line explanation (2 lines)
🔧 Subcomponents:
earthTexture = loadImage('https://raw.githubusercontent.com/mrdoob/three.js/r147/examples/textures/planets/earth_atmos_2048.jpg');
Fetches a high-resolution 2048×2048 pixel image of Earth from a CDN and stores it in the earthTexture variable
webglFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');
Loads the Roboto font from a CDN so that 3D text in WEBGL mode renders cleanly and readable
earthTexture = loadImage('https://raw.githubusercontent.com/mrdoob/three.js/r147/examples/textures/planets/earth_atmos_2048.jpg');- loadImage() downloads the image from the URL and stores it. This image will be wrapped around the Earth sphere later using the texture() function.
webglFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');- loadFont() downloads the font file from the CDN and stores it. p5.js needs this font loaded before setup() runs so text() calls in WEBGL mode will render properly.