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 path in your working directory. Here, we’ll use a video with the .mp4 format, which is a video file format that’s well-supported across most browsers.
let video; video = createVideo('myVideo.mp4');
As with images, we can store video elements as variables. Typically, we’ll do this in a place like the
preload() function so that we can use it later on in our sketch.
To play a video, you can use the
createVideo() function displays an HTML video element on the page, but not within the sketch itself.
To display the video directly within the p5 sketch, we can reuse the
image() function from before:
image(video, 0, 0);
It may be confusing to use a function called ‘image’ to draw videos—but it makes sense when we think of a video as a sequence of images. When called, the
image() function draws the current frame of the video on the canvas. When placed in the
draw() loop, we can create the illusion of a video playing, frame-by-frame.
Like with drawing images, you can resize the drawn video by adding two more parameters:
let drawnWidth = 100; let drawnHeight = 100; image(video, 0, 0, drawnWidth, drawnHeight);
To hide the original HTML video element, we can use the
This makes the original video invisible—but it doesn’t delete it! You’ll still be able to hear the video’s sound unless you turn off its volume. We’ll get to that in the next exercise!
Note that the
.hide() method will hide the video drawn on the canvas as well unless at any point you play the video. Until then, no video frames will draw to the canvas.
preload() function, load a video with the path given by the variable
videoPath, and save it to the variable
Run the code to see the HTML video element appear on the page.
mouseClicked() function, play the video. This video file has no sound, so you shouldn’t expect to hear anything!
After running the code, you should be able to play the video by clicking anywhere on the sketch.
draw() loop, display the video onto the canvas. You can position or scale the drawn video however you choose.
Note that for the drawn video to appear, you must draw it to the canvas after the
background() function is called.
Back in the
setup() function, hide the original HTML video element.
Note that now, the video will not display on the canvas until you make it play.