5. Media and Export
Beyond drawing shapes, p5.js allows you to integrate various media types and share your interactive art with others.
5.1. Working with Images
Load and display images using loadImage() and image(). Preload images in preload() to ensure they are ready before setup() runs.
let img;
function preload() {
img = loadImage('assets/p5js_logo.png'); // Make sure this path is correct
}
function setup() {
createCanvas(400, 400);
imageMode(CENTER); // Draw images from their center
}
function draw() {
background(220);
image(img, mouseX, mouseY, 50, 50); // Display image at mouse position, size 50x50
}
5.2. Integrating Video and Sound
Use createVideo() and loadSound() to add dynamic media. Remember to handle user interaction for playback due to browser autoplay policies.
let video;
let sound;
function preload() {
video = createVideo('assets/p5js_video.mp4'); // Path to video file
sound = loadSound('assets/p5js_sound.mp3'); // Path to sound file
}
function setup() {
createCanvas(400, 400);
video.hide(); // Hide the default video element
}
function draw() {
background(220);
image(video, 0, 0, width, height); // Display video frames on canvas
}
function mousePressed() {
// Start video/sound on user interaction
if (video.elt.paused) {
video.loop();
} else {
video.pause();
}
if (sound.isPlaying()) {
sound.pause();
} else {
sound.loop();
}
}
5.3. Exporting Your Creations
You can easily save frames or the entire canvas as an image or video.
function keyPressed() {
if (key === 's' || key === 'S') {
saveCanvas('mySketch', 'png'); // Save current canvas as 'mySketch.png'
}
if (key === 'r' || key === 'R') {
// For saving a sequence of frames for video, use capture libraries
// or manually trigger saveFrame() over time.
}
}
By following these steps, you are well-equipped to dive into the exciting world of creative coding with p5.js!