Skip to content

Commit

Permalink
feat: implement OffscreenCanvas.convertToBlob
Browse files Browse the repository at this point in the history
  • Loading branch information
jimmywarting authored and LinusU committed Jul 24, 2023
1 parent adf73ee commit 329ee9a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
29 changes: 28 additions & 1 deletion lib/canvas.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -111,3 +136,5 @@ Canvas.prototype.toDataURL = function (a1, a2, a3) {
return `data:${type};base64,${this.toBuffer(type, opts).toString('base64')}`
}
}

module.exports = Canvas

0 comments on commit 329ee9a

Please sign in to comment.