How to use images in p5.js
Image handling allows users to display and manipulate images. The p5.js library has built-in functions that allow for such interactions to take place.
Images
To use images, we’ll primarily be using two functions: loadImage() and image(). There is one nuance with the loadImage() function that it must be called in the preload() function rather than setup(). This is because loadImage() is an setup() might cause the application to start without successfully loading the image.
The setup() function is called once at the start of the execution. This function sets up the application canvas.
The preload() function
The preload() function is a special function called before the execution of the setup() function. This function waits for all preload() function to load assets like music, sounds, images, or videos.
We’ll call the loadImage() function in the preload() function. The loadImage() function takes in only one argument, i.e., the image’s URL.
Note: The image may be locally stored with the code, or hosted online (accessible through some API call). The function signature remains the same. In our example, we will be using an image hosted online.
The image() function
The image() displays the image onto the canvas. This function takes in five parameters. The signature of this function is:
image(img, x, y, width, height)
The
imgis anp5.Imageobject.The
xandyare the coordinates for the image.The
widthandheightare the width and height of the image.
Note: The
x,y,width, andheightare optional parameters. Their default values are:
x = 0
y = 0
width = width of the image loaded
height = height of the image loaded
The full signature of the function looks like image(img, dx, dy, dWidth, dHeight, sx, sy, [sWidth], [sHeight], [fit], [xAlign], [yAlign]), but this is only applicable in complex situations.
The fit parameter is not required. It allows us to draw a specific part of the source image without changing its shape. If we set fit to CONTAIN, the entire part will fit inside the destination rectangle. If we set fit to COVER, the part will cover the entire destination rectangle, similar to zooming in.
The xAlign and yAlign decide how to align the fitted part. xAlign can be set to LEFT, RIGHT, or CENTER, while yAlign can be set to TOP, BOTTOM, or CENTER. By default, both xAlign and yAlign are set to CENTER.
Let’s look at some examples:
Example: Loading an image
Take a look at the example below. We’re loading an image and displaying it onto the canvas.
Code explanation
Lines 1–5: The
imgvariable stores the image, which will be anp5.Imageobject. TheimgUrlstores the path to the image.Lines 8–11: In the
preload()function, we are using theloadImage()function to load the image from the pathimgUrl.Lines 14–23: In the
setup()function, we are using thecreateCanvas()function to create a canvas for the application. We use thebackground()function to set the background to240, which means a gray value of 255 (white). Then, we use theimage()function to display the image at coordinates0,0and size500, 120.Line 30: The
image()function displays a specific part of theimgon the canvas. The destination coordinates0, 300and dimensions200, 200determine where on the canvas the image is placed while the source coordinates300, 900and dimensions300, 300specify the portion of theimgimage to be shown. Optional parameters includefitset toCONTAIN, ensuring the image fits within the specified rectangle, andxAlignandyAlignset toCENTER, aligning the subsection both horizontally and vertically.
Example: Image position manipulation
Take a look at the example below. We’re loading an image and displaying it onto the canvas. The mouse position controls the position of this image.
Code explanation
Lines 1–8: The
xandyvariables store the position of the image.Lines 17–33: In the
setup()function, we set the variablesxandyto zero initially. We set theimageModetoCENTER. This puts the image coordinates in the center instead of the top-left corner.Lines 35–45: We redraw the background and image at each frame in the
draw()function. We set thexandytomouseXandmouseYrespectively. These are the coordinates of the mouse pointer.
Conclusion
The p5.js allows the user to work with images in a simple way. There are also other functions like the createImage()tint()
Unlock your potential: p5.js fundamentals series, all in one place!
To deepen your understanding of p5.js, explore our series of Answers below:
What is p5.js?
p5.js is an open-source JavaScript library for creative coding, designed for visualizations, games, and interactive art, with a beginner-friendly approach.How to color shapes in p5.js
Learn how to apply colors to shapes usingfill(),stroke(), and transparency to create stunning visual effects.How to use images in p5.js
Discover how to load, display, and manipulate images in p5.js to enhance dynamic and interactive sketches.How to use image filters in p5.js
Enhance your images with built-in filters like grayscale, blur, and threshold to achieve unique visual effects.How to create advanced 2D shapes in p5.js
Master the creation of complex 2D shapes using curves, vertices, and transformations for custom designs.How to add keyboard interaction in p5.js
Learn how to detect and respond to keyboard input to add interactivity to your sketches.How to use vectors in p5.js
Explore the power of vectors for motion, physics simulations, and dynamic interactions in creative coding.How to add mouse interaction in p5.js
Implement mouse-based interactions such as clicks, drags, and movement tracking to enhance user engagement.
Free Resources