0

I'm trying to create a generative canvas in p5js which has about 4 grid layout options controlled by a slider. The main canvas is square in ratio and made of squares, rectangles and circles. An image can be upload to the canvas.

Upon upload how can I get the uploaded image to be masked by one of the shapes on the grid? but also have the flexibility to be masked in the 2nd and 3rd grid option by a different shape? Each grid layout offers different spaces in which the image can be masked by a shape. Ideally the image should fit within the shape by width.

Thanks

shasofia
  • 1
  • 2

1 Answers1

0

The Image.mask function is probably the easiest way to do this. However, it permanently alters the image. So if you want to mask the same image multiple time with different shapes you need to make copies.

let img;
let img1;
let img2;
let img3;
let img4;

let mask1, mask2, mask3, mask4;

function preload() {
  img = loadImage('https://www.paulwheeler.us/files/windows-95-desktop-background.jpg');
}

function setup() {
  createCanvas(400, 400);
  background('lime');
  
  mask1 = createGraphics(img.width, img.height);
  mask2 = createGraphics(img.width, img.height);
  mask3 = createGraphics(img.width, img.height);
  mask4 = createGraphics(img.width, img.height);
  
  mask1.fill(0);
  mask1.ellipseMode(CORNER)
  mask1.circle(20, 20, 160);
  
  mask2.fill(0);
  mask2.square(20, 20, 160);
  
  mask3.fill(0);
  mask3.triangle(20, 180, 100, 20, 180, 180);
  
  mask4.fill(0);
  mask4.triangle(20, 20, 180, 20, 100, 180);
  
  img1 = createImage(img.width, img.height);
  img1.copy(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
  img1.mask(mask1);
  
  img2 = createImage(img.width, img.height);
  img2.copy(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
  img2.mask(mask2);
  
  img3 = createImage(img.width, img.height);
  img3.copy(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
  img3.mask(mask3);
  
  img4 = createImage(img.width, img.height);
  img4.copy(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
  img4.mask(mask4)
  
  noLoop();
}

function draw() {
  image(img1, 0, 0, 200, 200, 0, 0, 200, 200);
  image(img2, 200, 0, 200, 200, 0, 0, 200, 200);
  image(img3, 0, 200, 200, 200, 0, 0, 200, 200);
  image(img4, 200, 200, 200, 200, 0, 0, 200, 200);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>
Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41