Offscreen Render in Processing

October 25, 2021

For anyone who has tried to render stills or videos of large running Processing sketches, this post is for you. Many of the sketches that I create are performative in nature and develop with time and input. For this reason, seeing the entire sketch while its running is important to know what the file result will be. However, when I set the sketch size to 1080px x 1920px, I can no longer see the entire view of the sketch that is running because of the size of my monitor. I’ve come up with two solutions that might be useful for other Processing users.

Create a thumbnail

One approach is to create a thumbnail of the sketch using PGraphics and draw it into a smaller container. However, this is not ideal because we then have that thumbnail included in the final render if we decide to usesaveFrame();

PImage thumbnail;
PGraphics pg;

void setup(){
    size(1080, 1920);
    pg = createGraphics(width / 10, height/ 10);
}

void draw(){
    ellipse(width/2, height/2, 100, 100);

    thumbnail = get();

    image(thumbnail, 10, 10, width / 10, height / 10);
}

Offscreen Render

This option is noticablely better but requires a bit more work by using an offscreen canvas to render to. We use PGraphics pg to create a canvas to draw to, and resize that canvas to fit the viewport. This allows us to scale to whatever size we might need. There is also a performance benefit in that the primary canvas can be smaller, reducing the amount of cpu/gpu used.

PGraphics pg;

// We need to create variables for the width and height we want to use.
int scaleFactor = 2;
int w = 1080 * scaleFactor;
int h = 1920 * scaleFactor;

// In later versions of Processing, you need to use settings if you want to do any operations on the width and height
void settings(){
  size(w / 8, h / 8);
}

void setup() {
  pg = createGraphics(w, h);
}

void draw() {
  background(150);
  pg.beginDraw();
  pg.background(150);
  pg.ellipse(w/2, h/2, 100, 100);
  pg.endDraw();

  image(pg, 0, 0, width, height);

  if(keyPressed){
    if(key == 's') pg.save("image.png");
  }
}

The final result is an enormous 2160 x 3840 bitmap image that displays a beautiful circle.

View Gist Snippet

Offsreen render


Profile picture

Written by Matthew Ortega who lives and works in Valencia, Spain
Follow on Twitter

© 2021