<aside> 🤘 Creating a dynamic mask that reveals an underlying image with p5.js and Mediapipe Hands:

p5.js Web Editor

</aside>


Getting started

Here are a few key p5.js features that you will need to know how to use to create this effect:

pGraphics

reference | p5.js

Think of the pGraphics object as another canvas that you can draw on. This additional canvas is stored as an image object that you can place onto the main canvas using the image function.

var pg; // variable for the pGraphics object

function setup() {
	createCanvas(400, 400);
	
	// create a pGraphics object that is the same width and height of the main canvas
	pg = createGraphics(width, height);
}

function draw() {
	background(0);
	
	// to draw on the pGraphics object, first declare the object name (e.g. pg) 
	// followed by the same functions for drawing on the main canvas

	pg.clear(); // clear the pGraphics object (transparent background);
	pg.fill("red");
	pg.noStroke();
	pg.circle(pg.width/2, pg.height/2, 100); // draws a red circle in the middle of the pGraphics object
	
	image(pg, 0, 0, pg.width, pg.height); // place the pGraphics object onto the main canvas
}

The example above seems to be using pGraphics in a redundant way. After all, we can draw the same red circle on the main canvas without using pGraphics.

Hang on to that thought, things get interesting when we manipulate multiple pGraphics objects along with the main canvas simultaneously…

loadPixels()

reference | p5.js

The p5.js canvas is essentially an image that gets updated every frame in the draw loop. We can access and manipulate each individual pixel on the p5.js canvas (as well as pGraphics objects) by loadPixels(), pixels[], and updatePixels().