0

I have a simple game-loop that clips the canvas each iteration with a predefined Path2D to create an edge like this:

clip path example

The problem is that over time (~30sec) it starts to slow down in performance linearly.

Here is the game-loop code:

private loop(time: DOMHighResTimeStamp) {
if (!this.lock) {
  this.context.setTransform(1, 0, 0, 1, 0, 0);
  this.context.clearRect(
    0,
    0,
    this.context.canvas.width,
    this.context.canvas.height
  );

  this.viewport = {
    width: this.context.canvas.width,
    height: this.context.canvas.height,
  };

  if (this.scene) {
    if (this.clipPath) {
      this.context.clip(this.clipPath);
    }
    this.scene.update(this.inputs);
    this.scene.render(this.context, this.options?.debug);
  }
}


  this.fps = Math.floor(1 / ((time - this.previousTime) / 1000));
  this.previousTime = time;
  requestAnimationFrame(this.loop.bind(this));

}

The code of concern is below (this.clipPath is a new Path2D("...mypath...")):

if (this.clipPath) {
   this.context.clip(this.clipPath);
}

Removing this solves my issue but I would like to clip the canvas:

if (this.clipPath) {
   // this.context.clip(this.clipPath);
}

I know there are issues when you don't include context.beginPath() before working with canvas paths but the following code doesn't solve my issue:

if (this.clipPath) {
   this.context.beginPath();
   this.context.clip(this.clipPath);
}

Any ideas? Thanks.

Sam Scolari
  • 113
  • 1
  • 10
  • 1
    Use `ctx.save` to save unclipped state and then `ctx.restore` to remove clip area. If not you keep adding to the clip area. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/restore You could also use `ctx.reset` to remove clip but it does not have full browser support. – Blindman67 Mar 07 '23 at 00:34
  • Woops thanks, I was using restore and save inside my render loop but the clipping was happening outside of it. – Sam Scolari Mar 07 '23 at 00:58
  • 1
    Note that `beginPath()` only acts on the context's internal path-data, using Path2D objects allows you to not have to worry about that. – Kaiido Mar 07 '23 at 01:00

0 Answers0