Using mask to reveal background image

Hi, I’m trying to write a sketch that uses mask to temporarily reveal a background/bottom image when the mouse pointer moves but does not permanently draw over it.

I have a sketch written based on reading docs and looking at other people’s code but I can’t get it working. I can see that I have created the mask layer but I am struggling to get the background image to display in the ellipse.

My sketch in editor

var bgImage, topImage, mask;

function preload() {
  bgImage = loadImage(
    'https://mbkassets.s3-eu-west-1.amazonaws.com/dev/andy/TexturesCom_Camouflage0018_seamless_S.jpg'
  );
  topImage = loadImage(
    'https://mbkassets.s3-eu-west-1.amazonaws.com/dev/andy/TexturesCom_ConcretePlates0207_1_seamless_S.jpg'
  );
}

function setup() {
  createCanvas(400, 600);
  mask = createGraphics(width, height);
}

function draw() {
  // draw background image
  image(bgImage, 0, 0, width, height);
  // Draw mask shape
  mask.background(0);
  mask.ellipseMode(CENTER);
  mask.fill(255);
  mask.noStroke();
  mask.ellipse(mouseX, mouseY, 200, 200);
  // apply mask to top image & draw top image
  topImage.mask(mask.get());
  image(topImage, 0, 0, width, height);
}

I have created the same thing with CSS and JS in codepen but want to achieve this with p5.

Thanks in advance for any help.

Andy

code here

3 Likes

Thanks @noel, this is exactly what I was trying to achieve :+1:t2:

1 Like