preload()
preload() runs before setup() and is the only place where loadShader() and loadFont() will work reliably. Use it to prepare all assets your sketch needs.
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 (4 lines)
🔧 Subcomponents:
myShader = loadShader('vertex.glsl', 'fragment.glsl');
Loads the vertex and fragment shader files that will render the liquid-chrome effect
myFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');
Loads a WEBGL-compatible font from a CDN so text renders correctly in 3D mode
prevMouseX = mouseX;
prevMouseY = mouseY;
velocityX = 0;
velocityY = 0;
Sets up variables to track mouse movement and calculate velocity on the first frame
myShader = loadShader('vertex.glsl', 'fragment.glsl');- Loads two GLSL shader files: vertex.glsl (handles geometry) and fragment.glsl (handles colors and effects). This must happen in preload() before setup() runs.
myFont = loadFont('https://unpkg.com/@fontsource/roboto@latest/files/roboto-latin-400-normal.woff');- Loads a font from a CDN. In WEBGL mode, regular fonts don't work, so p5.js needs a special WOFF font file loaded before setup().
prevMouseX = mouseX;- Stores the initial mouse X position so we can calculate velocity (change in position) on the next frame.
velocityX = 0;- Initializes horizontal velocity to zero so the first frame doesn't have a garbage value.