From 329ee9a0641fc1cc341a221f2a4d0d1da8a4b1a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20Wa=CC=88rting?= Date: Wed, 5 Oct 2022 16:24:57 +0200 Subject: [PATCH] feat: implement OffscreenCanvas.convertToBlob --- CHANGELOG.md | 1 + lib/canvas.js | 29 ++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0768f8c3..78b2fc5da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ project adheres to [Semantic Versioning](http://semver.org/). * Add Node.js v20 to CI. (#2237) ### Added * Added string tags to support class detection +* Implemented `OffscreenCanvas.prototype.convertToBlob()` - Depends on global `Blob` support. (NodeJS 18+) (#1845) ### Fixed * Fix a case of use-after-free. (#2229) * Fix usage of garbage value by filling the allocated memory entirely with zeros if it's not modified. (#2229) diff --git a/lib/canvas.js b/lib/canvas.js index 03fa1a959..79c4aa202 100644 --- a/lib/canvas.js +++ b/lib/canvas.js @@ -7,13 +7,13 @@ */ const bindings = require('./bindings') -const Canvas = module.exports = bindings.Canvas const Context2d = require('./context2d') const PNGStream = require('./pngstream') const PDFStream = require('./pdfstream') const JPEGStream = require('./jpegstream') const FORMATS = ['image/png', 'image/jpeg'] const util = require('util') +const Canvas = bindings.Canvas // TODO || is for Node.js pre-v6.6.0 Canvas.prototype[util.inspect.custom || 'inspect'] = function () { @@ -44,6 +44,31 @@ Canvas.prototype.createJPEGStream = function (options) { return new JPEGStream(this, options) } +/** + * The OffscreenCanvas.convertToBlob() method creates a Blob object representing + * the image contained in the canvas. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas/convertToBlob + * @since NodeJS v18.0.0 + */ +Canvas.prototype.convertToBlob = async function (options = {}) { + // If the user agent does not support the requested type, then it must create the file using the PNG format. + // ref: https://html.spec.whatwg.org/multipage/canvas.html#a-serialisation-of-the-bitmap-as-a-file + const type = options.type && FORMATS.includes(options.type) + ? options.type + : 'image/png' + + const quality = options.quality != null + ? { quality: options.quality } + : undefined + + return new Promise((resolve, reject) => { + this.toBuffer((err, buf) => { + err ? reject(err) : resolve(new Blob([buf], { type })) + }, type, quality) + }) +} + Canvas.prototype.toDataURL = function (a1, a2, a3) { // valid arg patterns (args -> [type, opts, fn]): // [] -> ['image/png', null, null] @@ -111,3 +136,5 @@ Canvas.prototype.toDataURL = function (a1, a2, a3) { return `data:${type};base64,${this.toBuffer(type, opts).toString('base64')}` } } + +module.exports = Canvas