Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added feature to saveCanvas() to support framebuffer #6510

Merged
merged 7 commits into from
Nov 17, 2023
17 changes: 15 additions & 2 deletions src/image/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ p5.prototype.createImage = function(width, height) {
* file immediately or prompt the user with a dialogue window.
*
* @method saveCanvas
* @param {p5.Element|HTMLCanvasElement} selectedCanvas reference to a
* @param {p5.Framebuffer|p5.Element|HTMLCanvasElement} selectedCanvas reference to a
* specific HTML5 canvas element.
* @param {String} [filename] file name. Defaults to 'untitled'.
* @param {String} [extension] file extension, either 'jpg' or 'png'. Defaults to 'png'.
Expand Down Expand Up @@ -175,14 +175,26 @@ p5.prototype.saveCanvas = function() {

// copy arguments to array
const args = [].slice.call(arguments);
let htmlCanvas, filename, extension;
let htmlCanvas, filename, extension, temporaryGraphics;

if (arguments[0] instanceof HTMLCanvasElement) {
htmlCanvas = arguments[0];
args.shift();
} else if (arguments[0] instanceof p5.Element) {
htmlCanvas = arguments[0].elt;
args.shift();
} else if (arguments[0] instanceof p5.Framebuffer) {
const framebuffer = arguments[0];
temporaryGraphics = this.createGraphics(framebuffer.width,
framebuffer.height);
temporaryGraphics.pixelDensity(pixelDensity());
framebuffer.loadPixels();
temporaryGraphics.loadPixels();
temporaryGraphics.pixels.set(framebuffer.pixels);
temporaryGraphics.updatePixels();

htmlCanvas = temporaryGraphics.elt;
args.shift();
} else {
htmlCanvas = this._curElement && this._curElement.elt;
}
Expand Down Expand Up @@ -213,6 +225,7 @@ p5.prototype.saveCanvas = function() {

htmlCanvas.toBlob(blob => {
p5.prototype.downloadFile(blob, filename, extension);
if(temporaryGraphics) temporaryGraphics.remove();
}, mimeType);
};

Expand Down
Loading