Save only a certain area of canvas using p5.js

936 views Asked by At

I am wondering if it is possible to clip/save a specified area of the canvas to a local jpg/png file using P5.js. I'm aware of the save() function. However, as far as I know, it only saves the canvas as whole. Any ideas?

Thanks!

1

There are 1 answers

0
Kevin Workman On

You could do this:

  • Call the get() function to get the pixel values of a certain region
  • Use the createGraphics() function to create a buffer
  • Call set() on that buffer object and pass in the pixel array you created
  • Call save() and pass that buffer object in as the first argument

Here's a simple example:

let pg;

function setup() {
  createCanvas(100, 100);
  pg = createGraphics(50, 50);
}

function draw() {
  background(200);
  pg.background(100);
  pg.noStroke();
  pg.ellipse(pg.width / 2, pg.height / 2, 25, 25);
  image(pg, 25, 25);

}

function mousePressed(){
    save(pg, "test.png");
}

More info can be found in the reference.