Key Concepts

Review core concepts you need to learn to master this subject

The preload() Function

let img; function preload() { img = loadImage('myImage.jpg'); } function setup() { // Image is completed loaded when the setup function runs }

The preload() function can be used to load any media assets that need to be completely loaded before the setup() and draw() functions run.

Images and Videos
Lesson 1 of 1
  1. 1
    So far, we’ve learned to create dynamic p5.js sketches using only shapes and colors. But, just like how you might add external images or videos onto a normal webpage, you can also use the p5.js li…
  2. 2
    Unlike the primitive shapes we’ve drawn so far, media, like images, are considered external assets. To include them in our sketches, we will need to load them using special, built-in p5.js function…
  3. 3
    If you’ve ever web-surfed with poor internet connection—you know firsthand that images can take a while to show up, even if other parts of the page load just fine. This same behavior applies to p5…
  4. 4
    Now that we can add images into the canvas let’s learn how to add another major type of media: videos! To create a p5.js video element, use the createVideo() function. It requires the video file’s…
  5. 5
    Now that we can add videos to the canvas let’s take a look at some extra options p5.js gives us to control video options and playback. These options also build off of HTML and JavaScript’s existing…
  6. 6
    Adding photos and videos into the canvas is cool, but the real fun comes when we add effects to them through tools like filters. Filters in p5.js work in two ways: across the entire canvas and app…
  7. 7
    We can also use p5.js to manipulate images and videos, down to the pixel. p5.js offers built-in functions to do this: get() and set(). The get() function accesses the color of a specific pixel on …
  8. 8
    Before diving into more complex image manipulation techniques, let’s look at what’s happening under the hood with the get() and set() functions. The pixels array is a special data structure that e…
  9. 9
    As mentioned earlier, pixel density can affect how you read the pixels array. Since different monitors have different pixel densities, let’s make things uniform by working with a pixel density of 1…
  10. 10
    Once we have the pixels array, we need to know how to read and write to it. That requires correctly indexing into it to get the color values for each pixel. Because each pixel has four color value…
  11. 11
    In this lesson, we learned how to bring media into our p5.js Sketches with images and videos. We also learned how to play around with them through filters and pixel manipulation. Let’s take a mome…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo