xxxxxxxxxx
84
// Mask Function
p5.Graphics.prototype.mask = function(inputMask) {
if (inputMask === undefined) {
inputMask = this;
}
const currBlend = this.drawingContext.globalCompositeOperation;
let scaleFactor = 1;
if (inputMask instanceof p5.Renderer) {
scaleFactor = inputMask._pInst._pixelDensity;
}
const copyArgs = [
inputMask,
0,
0,
scaleFactor * inputMask.width,
scaleFactor * inputMask.height,
0,
0,
this.width,
this.height
];
this.drawingContext.globalCompositeOperation = 'destination-in';
p5.Renderer2D.prototype.copy.apply(this, copyArgs);
this.drawingContext.globalCompositeOperation = currBlend;
}
// -------------------------
// Sketch
let maskGraphics;
let drawingGraphics;
function setup() {
createCanvas(400, 400);
maskGraphics = createGraphics(width, height);
// setup mask graphics with circle mask
maskGraphics.fill(0, 255);
maskGraphics.circle(width / 2, height / 2, width / 2);
drawingGraphics = createGraphics(width, height);
drawingGraphics.rectMode(CENTER);
drawingGraphics.fill(0, 255, 0);
background(0);
}
function draw() {
// transparent background
rectMode(CORNER);
fill(0, 5);
rect(0, 0, width, height);
drawingGraphics.background(0, 0, 255);
// green filled in square on drawing graphics
drawingGraphics.square(
noise(frameCount * 0.005, 0) * width,
noise(frameCount * 0.005, 1) * height,
width / 2
);
// white outline square on canvas
rectMode(CENTER);
noFill();
stroke(255);
square(
noise(frameCount * 0.005, 0) * width,
noise(frameCount * 0.005, 1) * height,
width / 2
);
// Apply mask
drawingGraphics.mask(maskGraphics);
image(drawingGraphics, 0, 0);
}