What is the faster way of saving canvas' pixels or state for later use?

Viewed 1224

Because drawing objects with p5js every time draw() is called slows down my sketch I wanted to save a copy of my canvas without any moving objects, and then only redraw part of the background that was previously covered by the moving object whenever it moves.

I tried creating an array of colors using get() function and going down the whole screen in hopes that I could then just take a patch from that and replace whatever needed to be cleared to the way it was before. This would work but making a copy of the whole canvas, especially when my canvas takes up the whole screen of the browser, is very slow.

tl;dr I am trying to save my canvas to later patch up parts of the screen but it takes too long

var defaultScreenPixels;

function savePixels(){
  for(let i = 0; i < screenHeight; i++){
    defaultScreenPixels[i] = [];
    for(let j = 0; j < screenWidth; j++){
      defaultScreenPixels[i].push(get(j, i));
    }
    console.log("Saved " + i +" row(s) of the screen, " + (screenHeight - i) 
+" rows to go");
  }
}
1 Answers

p5js has a built-in API called createGraphics() which according to the documentation says Creates and returns a new p5.Renderer object. Use this class if you need to draw into an off-screen graphics buffer. The two parameters define the width and height in pixels. Which does what you are trying to do and most likely to be far quicker than doing it one pixel at a time.

See p5js.org/reference/#/p5/createGraphics for further details.

There is an example here where you use image() to copy the off-screen graphic buffer back to the screen. http://p5js.org/examples/structure-create-graphics.html

Related