Submodule 18.1: Image in p5.js I
Images in p5.js
There are two ways to include images in p5.js
The first way is to display an image after the image has been load.
In order to do that we go in the setup() function and we write the following code:
function setup() {
createCanvas(width, height);
loadImage('myfolder/myImage.jpg', function(myImg) {
image(myImg, 0, 0);
});
}
In the above code, inside the loadImage()
we have the path to the folder and the function to display the image. The function parameter myImg, holds as value our image.
The image(myImg, 0, 0);
is what displays the image. The 0,0 are the x and y coordinates where the image will be placed.
Using the above way, we may encounter some problems in our project because the image may not be immediately available for rendering.
If we want to first load the image and then start doing things with it, it is better to use the second way:
let myImg;
function preload() {
myImg = loadImage('myfolder/myImage.jpg');
}
function setup() {
createCanvas(width, height);
image(myImg, 0, 0);
}
The preload()
function should always be used before the setup() function. When used, the setup() waits until the loading has completed in order to start running.