p5.js preload() Function
Last Updated :
22 Feb, 2021
The preload() function in p5.js is used to asynchronously load files before the setup() function. It runs exactly once in when the sketch is loaded.
Most users do not use the preload() function as the same task can be done in setup() function. However, it is nice to separate similar code in our program to improve its scalability and modularity. Generally preload() function is used to load things like, images, 3D models, fonts, etc. in the sketch. The “loading…” text is displayed during the loading of the resources.
Syntax:
preload() {
// All loading calls here
}
Parameters: This function does not accept any parameters.
Below example illustrates the preload() function in p5.js:
Example 1:
Javascript
let gfg_img;
function preload() {
gfg_img = loadImage( '/gfg.png' );
}
function setup() {
createCanvas(400, 400);
}
function draw() {
background( 'green' );
image(gfg_img, 100, 100);
}
|
Output:
Example 2:
Javascript
let cylinder;
function preload() {
cylinder = loadModel( '/cylinder.stl' , true );
}
function setup() {
createCanvas(400, 400, WEBGL);
noLoop();
}
function draw() {
background( 'green' );
rotateX(90);
model(cylinder);
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...