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
15 changes: 13 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,24 @@ 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 = createGraphics(framebuffer.width, framebuffer.height);
davepagurek marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I think this all works in global mode! The last thing to do is to also make it work in instance mode, where createGraphics isn't globally defined. I think in that case using this.createGraphics will work though? Maybe try that and try using this in an instance mode sketch to verify

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 +223,7 @@ p5.prototype.saveCanvas = function() {

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

Expand Down
Loading