preload()
preload() runs once before setup() and is the only place where loadShader() and loadFont() should be called in p5.js. These are slow operations, so they must happen upfront before the sketch starts drawing.
function preload() {
// Load the custom shaders
// Ensure 'vertex.glsl' and 'fragment.glsl' files are present and contain GLSL code
myShader = loadShader('vertex.glsl', 'fragment.glsl');
// Load a font for text in WEBGL mode
// Using Fontsource CDN for reliable WEBGL-compatible fonts
myFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');
// Initialize velocity variables for the first frame
prevMouseX = mouseX;
prevMouseY = mouseY;
velocityX = 0;
velocityY = 0;
velocityMagnitude = 0;
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
myShader = loadShader('vertex.glsl', 'fragment.glsl');
Loads two GLSL files that define how vertices and fragments (pixels) are rendered—the heart of the visual effect
myFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');
Loads a web-friendly font file so text displays correctly in WEBGL mode
prevMouseX = mouseX;
Stores the mouse position at startup so the first frame's velocity calculation has valid previous coordinates
myShader = loadShader('vertex.glsl', 'fragment.glsl');- Loads two GLSL shader files from your project folder. The vertex shader processes geometry, the fragment shader calculates pixel colors. These files must exist alongside sketch.js.
myFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');- Loads a web font from a CDN (online source) because WEBGL mode requires specially formatted fonts—regular fonts won't work in WEBGL.
prevMouseX = mouseX;- Saves the current mouse X position so on the first draw() frame, we can calculate velocity by comparing previous position to current position.
prevMouseY = mouseY;- Saves the current mouse Y position for the same reason as prevMouseX.
velocityX = 0;- Initializes horizontal velocity to zero—before any mouse movement, there is no motion.
velocityY = 0;- Initializes vertical velocity to zero for the same reason.
velocityMagnitude = 0;- Initializes the total speed (magnitude) to zero—this value will be recalculated every frame based on how far the mouse moved.