Can shapes be limited by a border inside the canvas?

The following sketch sets up my question https://editor.p5js.org/cottonchipper/sketches/f7yKwh53v

background(220);
  fill('red');
  rect(0,0,200,200);
  rect(200,200,200,200);
  fill('white');
  const y = (400)/2 + sin(frameCount * 0.05) * 100;
  ellipse(100, 100, y, y);
  

It creates an ellipse that expands and contracts inside a rectangle drawn on the canvas.

My question is whether there is a way to make the edges of the ellipse flatten when they reach the edges of the rectangle, instead of overlapping onto the neighboring rectangle.

In this example, the rectangle and ellipse are in the corner of the canvas, but I would want to do the same in any area of the canvas. Essentially, I want to create a grid and move shapes within the cells, but not allow any part of a moving shape to be visible in a neighboring cell.

A good function to look into is the clip() function, which limits which pixels on screen are updated by drawing functions like shape() or image(). If you set the clip bounds to the cell you want to draw in, you will only be able to draw in that cell. Clip bounds are affected by rectMode() when you set them.

I’ve amended my sketch to use createGraphics() to achieve what I wanted.

let graf;
function setup() {
  createCanvas(400, 400);
  graf = createGraphics(200,200);
  
}

function draw() {
  background(220);
  fill('red');
  rect(0,0,200,200);
  rect(200,200,200,200);
  graf.background('red');
  graf.fill('white');
  const y = (300)/2 + sin(frameCount * 0.05) * 100;
  //graf.noStroke();
  graf.ellipse(100, 100, y, y);
  image(graf,200,200)
}