# How to Load Data with p5.js (2.0)

## Метаданные

- **Канал:** The Coding Train
- **YouTube:** https://www.youtube.com/watch?v=25omXt_OjD4
- **Просмотры:** 10,976

## Описание

This video covers how to load external assets like images, JSON files, and data from APIs into your p5.js 2.0 sketches. Learn the fundamentals of asynchronous operations in p5.js using Promises with async/await. Code: https://thecodingtrain.com/tracks/p5js-2.0/p5js-2.0/loading-data

🚀 Watch this video ad-free on Nebula https://nebula.tv/videos/codingtrain-how-to-load-data-with-p5js-20

p5.js Web Editor Sketches:
🕹️ Loading a Single Image: https://editor.p5js.org/codingtrain/sketches/NPKPIYhBR
🕹️ Sequential Loading: https://editor.p5js.org/codingtrain/sketches/lQxT7PTKC
🕹️ API and Loading Animation: https://editor.p5js.org/codingtrain/sketches/M_NGGyqr4
🕹️ Parallel Loading with Promise.all: https://editor.p5js.org/codingtrain/sketches/MgrJuSvJt
🕹️ Loading images with placeholders exercise: https://editor.p5js.org/codingtrain/sketches/Ur6plDyKK

🎥 Previous: https://youtu.be/0Ad5Frf8NBM
🎥 Next: https://youtu.be/1KqQeqZ3R9Y

References:
📖 p5.js 2.0 Beta: https://beta.p5js.org/
📖 Promise.all: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
🎨 Dog API: https://dog.ceo/dog-api/

Videos:
🚂 https://youtu.be/0Ad5Frf8NBM
🚂 https://youtu.be/QO4NXhWo_NM
🚂 https://youtu.be/AwyoVjVXnLk

Timestamps:
0:00:00 Hello!
0:00:54 How to Load an Image in p5.js
0:02:16 Asynchronous Code: promises, async, and await
0:04:10 Common Mistakes to Avoid
0:05:51 Loading Data from a Live API
0:08:21 Loading Multiple Items in a Sequence
0:09:12 Creating a Custom Loading Animation
0:13:39 Faster Parallel Loading with Promise.all()
0:16:48 Challenge for you!

Editing by Mathieu Blanchette
Animations by Jason Heglund
Music from Epidemic Sound

🚂 Website: https://thecodingtrain.com/
👾 Share Your Creation! https://thecodingtrain.com/guides/passenger-showcase-guide
🚩 Suggest Topics: https://github.com/CodingTrain/Suggestion-Box
💡 GitHub: https://github.com/CodingTrain
💬 Discord: https://thecodingtrain.com/discord
💖 Membership: http://youtube.com/thecodingtrain/join
🛒 Store: https://standard.tv/codingtrain
🖋️ Twitter: https://twitter.com/thecodingtrain
📸 Instagram: https://www.instagram.com/the.coding.train/

🎥 https://www.youtube.com/playlist?list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH
🎥 https://www.youtube.com/playlist?list=PLRqwX-V7Uu6Zy51Q-x9tMWIv9cueOFTFA

🔗 p5.js: https://p5js.org
🔗 p5.js Web Editor: https://editor.p5js.org/
🔗 Processing: https://processing.org

📄 Code of Conduct: https://github.com/CodingTrain/Code-of-Conduct

This description was auto-generated. If you see a problem, please open an issue: https://github.com/CodingTrain/thecodingtrain.com/issues/new

#asyncawait #promises #p5js2 #loadingimages #api #json #promiseall #p5js #javascript
=====================================================

## Содержание

### [0:00](https://www.youtube.com/watch?v=25omXt_OjD4) Hello!

Hi, welcome. In this video, I'm going to show you how to load things into your p5 js sketch. What I mean by things like load an image, load a JSON file. What's a JSON file? You might be asking this question. That's okay. Load from an API, some other web service. What's the weather today? What are the headlines from a news service? How do you get stuff from somewhere else into p5 js? And this video is specifically for if you're using p52. Hopefully, you're watching this in the future where of course you're using P52, but at current time we're in a little bit of a P51 transition to P52 phase. If you are a P51 user and you want to learn how to make that transition, I did make a separate video that shows you how to do the transition. But here, I'm just assuming using P52. All right, let's get started with the first thing you might want to do, which is show an image in your p5 js sketch. I have an image here

### [0:54](https://www.youtube.com/watch?v=25omXt_OjD4&t=54s) How to Load an Image in p5.js

on my desktop of Choo Choobbot. The first thing if I want to load that image into my p5 js sketch is to bring it into the p5 web editor itself. I can click here to open the sketch files navigation. I can click the plus symbol to upload a file and then I can go to the finder and grab that file and drag it in. And there it appears over there in the navigation. I can click on it to double check there's the image. So now I'm on the p5 js reference which I'm filtering by the keyword load. So I could see load model, load font, load image, load JSON, load strings, load bytes. All of these functions work the same way. I should also mention at the time of this recording I'm using the beta reference for 2. 0, but you might be watching this in the future where 2. 0 is the default version. This would be in summer 2026 and thereafter where this will just be at p5. org. So, let's go look at the load image page. I would encourage you to read it. It's going to have all the information that I'm covering in this video, but I'm not going to look at it now because I'm just going to show you. So, I need a variable to store a reference to the image. I'll declare that as a global variable. I'll just call it img. And then in setup, I'm going to call the load image function and give it the name of my image. Now

### [2:16](https://www.youtube.com/watch?v=25omXt_OjD4&t=136s) Asynchronous Code: promises, async, and await

let me go back to that reference. This sentence is key here. The function returns a promise and should be used in an async setup with a wait. Let me explain that to you. Load image returns a promise. What do you mean? Doesn't it just return the image? No. This is what's known as an asynchronous event in JavaScript. Create canvas is a synchronous event. We don't have to treat it any differently. But load image starts a process. It makes a network request. It loads the file. It reads the bytes of the file. it packages them up into the image. So this is something that potentially needs to be handled in different kinds of ways. The way in JavaScript to handle an event like that is typically with something called a promise. What a promise is something that's behind the scenes of p5 and you don't have to worry about it. But essentially load image doesn't actually return the image. It returns a promise that says I will in the future deliver this image to you. And what you want, what I want is the promise fulfilled. The way to receive the promise fulfilled is with the keyword await. So the load image function is a special kind of function that requires the keyword await. If you have functions in setup that require the keyword await, that are asynchronous functions that fulfill promises, you need to tell p5, JavaScript in advance that those will be there. And that is done with the async modifier. So now this is the full code. I'm going to make my setup function asynchronous. I'm going to call load image and wait for it to finish before the data is put in the image variable. And then I will move on to draw. What am I going to do in draw? Maybe I want to draw that image. And there you go. There's my little choo

### [4:10](https://www.youtube.com/watch?v=25omXt_OjD4&t=250s) Common Mistakes to Avoid

bot. So there's a couple really common mistakes that I've made. so many times now working with loading data this way and I just want to show them to you in case you end up making the same mistake yourself. So the first one is forgetting the async keyword. The good news about that if you forget that it's going to give you a nice error message here. Await is only valid in an async function. You can even see here there's like a red squiggle there that's kind of showing you there's some mistake. So that just means ah I forgot the async keyword. The harder mistake is if you forget await in the first place. And it doesn't matter whether you have async or not, but what I more commonly forget is just to add await or async. So if I wrote my code this way, which looks like it should work and run it, it fails. Now, the good news is p5 is set up to give you this friendly error message. So it's actually telling me what I've forgotten. Did you mean to put a wait before a loading function? But let's look at why this fails. If I console log the image here, you can see that what I've actually logged is the promise. So what I put in the variable is the promise that eventually this image will be loaded, which is not a thing you can draw in draw. You can't draw a promise. You can only draw the image. So this is where we have to await for that promise to be fulfilled. Once I have a wait, I have to remember to add a sync. And now if I run this again, we are good. And you can see the console log right that finished loading. It's console logging all the information about that image. If you want to learn more about promises and the lower level details about how they

### [5:51](https://www.youtube.com/watch?v=25omXt_OjD4&t=351s) Loading Data from a Live API

work as well as async and await. I do have another video series which I go through that in detail. I use a different JavaScript function for loading data called fetch. You're welcome to watch those. But for loading stuff in p5, that's all the information that you really need. Let's look at another scenario, a little bit more sophisticated, and I'm going to use this API called the dog API, the internet's biggest collection of open source dog pictures. So, this is a very simple API where you take this URL. I'm going to bring it into my p5 js sketch. Let's comment out the image for right now. I'm going to here in setup I'm going to make a variable called JSON. I'm going to say load give it that URL. And let's log the JSON. Ah, did I do that on purpose or not? I forgot. Look, I only have the promise of the JSON. That's not what I want. I want the JSON. So, I need to await that. Now, look what I have. I have this JavaScript object that has two properties, a message and a status. Now, guess what I can do? I could say, hey, image await load image that JSON's message. And let me put drawing the image back. And look, there's my dog. Now, let's uh not my dog, but my the picture of the dog that I got from the API. Let's just draw the dog the full size of the canvas. So this is one of the nice things about using this await async pattern is it allows me to step through multiple calls that of data that might be related to each other one at a time. Now what if what I want to do is load a 100 dog images. I'm going to make an array and I'm going to write a loop. Let's just do 10. And I can put both of these in sequence. So 10 times call the API, get the image, and then push those images into my array. Now, depending on when you're watching this video, you might not have learned about arrays yet because this could be relevant for just loading an image. But, you know, stop now, go learn about arrays and come back or vice versa. But just to acknowledge that. Now in draw, let me draw all those images and I'll put them somewhere on the canvas. Make it small. I'm going to add no loop. Just do it once.

### [8:21](https://www.youtube.com/watch?v=25omXt_OjD4&t=501s) Loading Multiple Items in a Sequence

Great. I have a collection of 10 images. Let's try 20 images. Oh my goodness. Oh, I had to wait so long. What if what I want to do is actually let draw start immediately and show some kind of progress bar instead of having it just wait for setup to finish and draw to move on. The way to do that is actually to take all of the loading code outside of setup. So I'm going to take all of this loading code outside of setup because I don't want setup to be an asynchronous function that's waiting for things anymore. I'm going to write a function called load stuff and I'm going to put all that code back in that function. Then I'm going to make that function asynchronous and I'm

### [9:12](https://www.youtube.com/watch?v=25omXt_OjD4&t=552s) Creating a Custom Loading Animation

going to call load stuff in setup. So essentially I created a separate function that loads things asynchronously with the await keyword one at a time in sequence and then I'm triggering that in setup without a wait so that draw can start immediately. I just want to doubly emphasize what I just said without await. I could put the await keyword with load stuff, but the whole point of moving everything outside into a separate async function is to now have a regular setup. Again, no async, no await. Load stuff starts the asynchronous calls inside of the load stuff function, but moves directly to draw. Let's run this now. So, I was expecting an error because we went straight to draw, but the images aren't ready. Well, when we went straight to draw, the length of the array was zero. So, there's no loop, no error. It just stops looping and it's done. But the images aren't loaded. They never get drawn. So, I need to fix that. I could leverage the fact that I could check how much of the array is ready. But for right now, let's just do the following. I'm going to create a variable called data loaded equals false. At the end of load stuff, I'm going to say data loaded equals true. Then in draw, we need draw to loop because I whole point is I want draw to start and animate something until data loaded equals true. Now I'm going to check if data is loaded, draw all the images. Otherwise, draw a loading bar. Let's How do I do that? Let's draw a rectangle. 0 0. Let's fill that rectangle with the color black. I'm going to draw it across the top or just across the whole thing. I'm going to just say with height right now. So, let me just load five dog images. There's no animation here, but let's see what happens. And then I'm going to put the no loop here. Once I have the images, I'm going to stop draw from looping, which might not be what you want to do, but I'm going to do it here. Okay. So, I see that black rectangle until the images are ready. How wide should that rectangle be? Well, I could just do an animation of something spinning, but because I'm loading an array here, could do something a little bit more sophisticated, I could check how many things are in the array so far because I'm adding them one at a time. Let width equal map dogs. length, length which should have a range from 0 to five to zero to the width of the canvas. And now draw the loading bar with that width. Let's do 20 images. Let's see what happens. Oh, I mapped it to five. If I'm going to do So that should be a variable somewhere. But if I'm going to load 20, my mapping has to be with 20. There we go. So, a little bit crude of an interface, but you can see how this pattern works. You can create your own separate function called load stuff to put all your loading data in it. You can keep track of things that are happening in that function with a boolean variable or by tracking the length of an array. And then you can essentially in draw decide what to do based on the current state of that loading function. And the key here is setup doesn't have async and await. The separate loading function does. Again, much simpler to have just done what I did at the start of this video where I just load everything in setup with async and await. Don't need all these extra variables and tracking everything. But if you want to have a custom animation that's happening while you're loading, this is something you could consider doing. A couple other things I should point out here. One is it's generally not the best practice to just like flood an API with a lot of calls all at once. So, you know, I think the dog API can handle our asking for 20 images just from this little p5 example. But that's something to think about depending on what kind of service you're actually using and what its requirements and constraints are. I should also note that there's no error checking here. If one of the URLs of one of those images comes back and is an invalid image, this whole thing might break. So, you know, that is something that I might need to think about as a future update to this example. And love to hear your questions and thoughts about that in the comments. All right, I want to demonstrate one

### [13:39](https://www.youtube.com/watch?v=25omXt_OjD4&t=819s) Faster Parallel Loading with Promise.all()

thing to you. This is a sketch from my objects and images tutorial. It was actually written with an earlier version of p5 1. 0, but I've rewritten that example to use async and await to load all the images. And it works. There are five kitten images here in the p5 web editor. The for loop loads all five of them with await load image. And the bubble objects are created each to display a random kitten image. So this sketch works. I don't need to change anything about it. But I do want to point out that this is actually not as efficient as it could be. So with five images, it really doesn't matter. But it has to load them all one at a time. It can't load kitten one until kitten zero is finished. It can't load kitten two till one and zero are finished. That's what's happening in this for loop. Await await await. Something I could do to make this faster is to allow the system to start loading all the images in parallel. How do you do that? Well, the way that I do that is by making an array. I could call that promises. And instead of putting the fulfilled loaded image into each spot in the kitten array, I'm going to put the promise of the image without a weight into that array. So now I have an array with no images in it but just with a collection of promises. All of the loading has started. All of the promises are going. I can then use a special JavaScript function. This is not part of p5. This is from JavaScript itself called promise. all to take the result of all of them when they are finished. So kittens now equals promises. all all of the promises. So this is a special way to instead of loading the images one at a time to collect all the promises to start them all loading but then wait to fill the array until they're all finished. And I think this should work. Let's try it. No. What did I do wrong? Oops. It's not promises. all. It's promise. all. Okay. Oh, and I made the classic mistake again. I need a new song. Instead of this dot song, I need the await song. There we go. And just to emphasize again, yes, I forgot the await keyword with promise. all, but the whole point is that there is no await keyword with load image. I want to start loading all of the images in parallel, but I want to wait for them all to finish. So, something you need to think about as you start to build more complex loading systems is not just about where the keyword await needs to be, but where you want to choose not to use it. So, this is a nice pattern that you can use if I were loading hundreds of images or in certain scenarios, this would be much more efficient and faster than loading them one at a time. Now, I'm going to give you a really hard exercise. This is

### [16:48](https://www.youtube.com/watch?v=25omXt_OjD4&t=1008s) Challenge for you!

a technical exercise. I'll provide a solution in this uh video's description. How would you have this sketch go to draw immediately and instead of a loading bar, the bubbles all appear, but they're empty frames and as the kitten images are loading, they start to populate. Think about that. Give that a try. So, there's so much more to the specifics of all the different kinds of things you could load into P5 and how you might use them. Hopefully, those will appear in other videos and things that I'm making. If you're confused, which you might be, that's okay. Please ask your questions in the comments or come over to the coding train discord. Would love to hear from you. And I'll see you next time on the coding train.

---
*Источник: https://ekstraktznaniy.ru/video/20665*