Dynamically Sized Canvas in Processing 3

In Processing 3, the size() command expects dimensions to be explicitly provided as constants (not as variable expressions). This makes it difficult to have a script that works with an image of an unknown size and then which sizes the canvas to match the image.

It is possible to do this, but it requires some new techology in Processing 3, based on using a built-in surface variable, demonstrated as follows:

PImage slu;
int w,h;

void setup() {
// Can either load an image stored locally, as follows:
//  slu = loadImage("campus4.jpg");
// Or can load an image from a URL as follows:
  slu = loadImage("http://business.slu.edu/uploads/2012/11/08/slu-homepage-campus4.jpg");

  w = slu.width;
  h = slu.height;
  surface.setResizable(true);
  surface.setSize(w, h);      // allows size of the canvas to change to fit the image
}

void draw() {
  image(slu, 0, 0);
}

When using this technique, you may not draw on the resized image until after the setup() function is done executing, which means that this must instead be done through something like the draw() function.


Michael Goldwasser
Last modified: Monday, 11 April 2016