Search code examples
maskmaskingp5.jsclipping

masking, or clipping mask with p5.js


I want to use one shape (for instance a rectangle) to act as a mask or clipping path for another shape (for instance a circle, or line) in P5.js

I can see solutions for using images as masks, but not shapes. It seems mask() is not a function of shapes: https://p5js.org/reference/#/p5.Image/mask


Solution

  • yes, you can.

    • create an extra rendering context with createGraphics().
    • In the draw loop draw something to this context which will be your mask. Whatever should be visible in your result has to be colored with the alpha channel, for example fill('rgba(0, 0, 0, 1)'.
    • Apply the mask to your original image myImage.mask(circleMask).
    • Your original image has now been modified by the mask, render it on the screen: image(myImage, x, y, w, h)

    Here is a working code example:

    let circleMask;
    let myImage;
    
    function setup() {
      createCanvas(400, 400);
    
      circleMask = createGraphics(128, 128);
    
      myImage = loadImage('FzFH41IucIY.jpg');
    }
    
    function draw() {
      background(255);
    
      circleMask.fill('rgba(0, 0, 0, 1)');
    
      circleMask.circle(64, 64, 128);
    
      myImage.mask(circleMask);
    
      image(myImage, 200 - 64, 200 - 64, 128, 128);
    }