masking, or clipping mask with p5.js
Asked Answered
S

2

5

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

Seagrave answered 8/4, 2018 at 8:22 Comment(0)
M
12

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);
}
Macedonia answered 13/12, 2019 at 13:20 Comment(0)
C
4

There isn't a way to do this out of the box with P5.js.

Right now your question is more of a math question than it is a P5.js question. I'd recommend searching for something like "circle rectangle intersection" for a ton of results, including this one: Circle-Rectangle collision detection (intersection)

Depending on what you want to do, you could get away with drawing the shapes to images and then using those images as a mask. But more likely you're going to have to calculate the intersection yourself. You might be able to find a library that does this for you, but again, there isn't a simple out of the box way with P5.js.

Cirone answered 9/4, 2018 at 15:26 Comment(1)
thanks for the detailed reply. I switched this particular project to paper.js as it provides much more useful vector manipulation than P5.js. However P5.js is particularly useful for other aspects of the same project. It seems to be something that would be a very useful feature for many.Seagrave

© 2022 - 2025 — McMap. All rights reserved.