P5.js: Save only part of the canvas

How can I save/download only a part of the canvas (save a cropped part of the whole image)?

e.g.

function setup() {
	createCanvas(windowWidth, windowHeight);
	background(255);

}

function draw() {
	ellipse(mouseX, mouseY, 20, 20);
}

function keyPressed(){
	if(key === 's'){
        	saveFrame(frameCount, "png"); 
        }    
}

Here the browser will prompt you to (or automatically start to) download an image of the entire sketch–is there any way I can only save a specific part?

1 Like

Put the part you want to save into a PImage using get(), then save it:

PImage to_save = get( 20, 30, 100, 200 ); // Grab an image of a 100x200 rectangle at (20,30).
to_save.save("saved_name.png");
1 Like

Ah! Thanks @TfGuy44.

This worked for me:

var saveCanvas;

function setup(){
  ...
  saveCanvas =  createGraphics(height, height);
}

function draw(){
  ...
}

function keyPressed() {
  if (key == 's') {
    let c = get(width/2-height/2,0, height, height);
    saveCanvas.image(c, 0, 0);
    save(saveCanvas, frameCount+".png");
  }
}
1 Like

Though for some reason the images from this are of lower quality than a regular save()?