Unit 1 Loops, Arrays, Media
Learning Activity 1

Loading media files: preload and callbacks


Overview

This learning activity demonstrates asynchronous calls and the need to use p5`s preload function or callback functions to make sure media files are fully loaded before trying to access them in our sketches. We will not be doing any coding yet.

Suggested Duration

15 minutes

Instructions

1. Loading files

p5 can draw images, text with certain fonts, and play sounds. In order to display (or play) them, it must first load the file in question. Take a look at the sketch below: we load the pupper.jpg file within setup(), and then call the image function to draw it in draw. From this code, one would expect to see an image in the sketch. However, chances are you are only seeing the gray background.

Why is this happening? Let's look at what loadImage does in more detail. The file pupper.jpg is stored in on a server computer somewhere on the web. loadImage makes a request to the server to send the file to the computer where p5 is running. Image files can be sizeable: the transfer takes some time. This would not be a problem if Javascript, the language we are programming in, was synchronous ––if, after calling a function, it paused running until that function has finished doing its task. Javascript, however, is asynchronous. After we call loadImage, and while the transfer is still not complete, p5 goes on to execute the lines that come next on our program: it creates the canvas (line 5), and continues to the draw function, where it draws the gray background (line 10), and attempts to draw pupper.jpg, most likely before it has been fully transfered to our computer.

2. Use preload()

To solve this problem, p5 adds another step to our familiar setup() once, and draw() forever program flow: the preload() function. When it runs our sketch, p5 calls preload() first, and then pauses execution until loadImage has finished loading our image file. In the following example, we place our call to loadImage within the preload function, to make sure that the image drawing function will never be called before pupper.jpg is fully loaded.

3. Use a callback function

In some cases, we do not know which image we need to load at the time we are writing the code. Perhaps it comes from a social media account that updates while our sketch is running, after preload has been called. In cases like this, we can use a callback function. Instead of placing our call to loadImage within the preload function, we place it in our setup or draw functions as appropriate, passing an extra parameter to it. This second parameter is the name of the function p5 should call once loadImage is done. In this case, we called it imageLoaded. Within this function, it is safe to draw the image to the canvas.

Both the preload and callback techniques apply to any other type of media files that need to be loaded into your sketch, such as sound or font files.