Snapshot of a canvas as an image in P5JS?

I'm wondering if there's an easy way to record a snapshot of the canvas as an image, but NOT trigger the "save" dialog in the browser. I'm aware of save() and saveCanvas(), and maybe there's a way to manipulate those functions to work for me.

e.g., I'd like to capture still frames of a canvas at various moments in time, and immediately create new DOM elements on my page that contain these images. Think of an image gallery that populates itself in real time, generatively.

Hopefully I'm articulating my idea clearly, and apologies if I'm overlooking something obvious!

Thank you

Answers

  • Answer ✓

    From the reference @GoToLoop linked to:

    Capture a sequence of frames that can be used to create a movie. Accepts a callback. (my emphasis)

    What isn't made clear is that the callback is passed an array containing the captured frames: you have to dig in the p5js source to discover that:

    //line 248
    if (callback) {
      callback(frames);
    }
    else {
      for (var i = 0; i < frames.length; i++) {
        var f = frames[i];
        p5.prototype.downloadFile(f.imageData, f.filename, f.ext);
      }
    }
    

    So create a callback function that accepts a frames parameter and works through the frames array that's passed to it:

    var processSavedFrames = function(frames) {
      for (var i = 0, len=frames.length; i < len; i++) {
        var f = frames[i];
        // do stuff with f...
      }
    }
    

    You'll have to experiment (or dig further into the source) to see what format f.imageData is in...

  • Thank you both! This is exactly what I needed. I appreciate your quick response.

  • Hi, I also need to save an image taken from the canvas, but save it on a specific folder in my server. saveFrames would be the solution? I don't understand where to tell the saveFrame the address destination for the images generated. Thanks for the help

  • By default saveFrames will invoke the browser's save dialogue. This is a very bad thing :(

    In the processSavesFrames callback described above frames[i] should be a reference to the image file. You'll have to add some code that passes the image to the server (e.g. using ajax POST request) below // do stuff with f...

Sign In or Register to comment.