Backbuffer in p5js

That is great and indeed this is a difficult example to make by yourself!

One suggestion would be to use two p5.Graphics objects. Right now you copy canvas to backbuffer then render canvas. This works perfectly in your case. But this becomes problematic if you want to use more layers - for example, if you draw a text on top of the canvas, this will affect the backbuffer in the next frame. If you prepare, say, backbuffer0 and backbuffer1, you can do something like this (I haven’t tested the code)

function draw() {
  backbuffer0.shader(sh_render);
  sh_render.setUniform("buffer", backbuffer1);
  ...
  backbuffer0.rect(0, 0, width, height);

  image(backbuffer0, width * -0.5, height * -0.5, width, height);

  [backbuffer0, backbuffer1] = [backbuffer1, backbuffer0]; // swap
}

this is so-called ping-pong (because it’s like a ping-pong rally) and useful because, as I mentioned above, they are not dependent on what is drawn on canvas.

1 Like