P5.js: Save only part of the canvas


#1

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?


#2

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");

#3

Ah! Thanks @TfGuy44.


#4

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");
  }
}

#5

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