Best way to export a sprite sheet from p5.js animation frames?

Hi everyone, I’m learning p5.js and building a small 2D game with animated characters. I have the character frames drawn across multiple draw() frames, and I’d like to export them as a single sprite sheet PNG I can reuse elsewhere. I tried using saveFrames() and stitching the images manually, but it feels clunky once you have dozens of frames. Is there a recommended approach or library for capturing frames and packing them into a sprite sheet grid directly from a sketch? Any examples or tips would be much appreciated. Thanks!

Hello!

And welcome to the forum, great to have you here!

I think the easiest is to collect the images with get() in an ArrayList.

Then make a sprite sheet from the list.

Here is an example.

Warm regards,

Chrisir


// https://discourse.processing.org/t/best-way-to-export-a-sprite-sheet-from-p5-js-animation-frames/49597

int mode = 0; // state
int x = 30;
ArrayList<PImage>list = new ArrayList();

PImage result = createImage(300, 500, RGB);

//-----------------------------------------------------------------------------------------------

void setup() {
  // Voller Bildschirm statt size()
  fullScreen();

  background(0) ;
}

void draw() {
  background(0) ;

  if (mode==0) {
    // collect list
    circle ( x, 290, 18);

    PImage img = get();
    img.resize(100, 0);
    list.add(img);
    x+=15;

    if (frameCount > 50)
      mode = 1;// go on
  }//if

  if (mode==1) {
    // show list / press any key 
    x=0;
    int y=0;
    int k=0;
    for (PImage img1 : list) {
      image(img1, x, y);
      text (k, x+20, y+20);
      x+=100;
      k++;
    }
    text ("Press any key.", 20, height-20);
    if (keyPressed) {
      mode=2;
    }
  }//if

  if (mode==2) {
    // make sprite sheet

    x=0;
    int y=0;
    int k=0;
    for (PImage img1 : list) {
      result.set( x, y, img1 );

      // next image pos to the right
      x+=100;

      // end of line?
      if ( x >= 300) {
        // next line
        x=0;
        y+=img1.height;
      }
      k++;
    }
    mode=3; // go on
  } //if

  if (mode==3) {
    // show sprite sheet 
    image (result, 0, 0);
  }
}//func
//

@lovelycraftguides, note that @Chrisir’s example above for Processing Java. The same general approach should still work in p5.js though, just using p5.Image, p5.Graphics, or p5.Framebuffer instead.