Skip to content

Commit 329ee9a

Browse files
jimmywartingLinusU
authored andcommitted
feat: implement OffscreenCanvas.convertToBlob
1 parent adf73ee commit 329ee9a

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ project adheres to [Semantic Versioning](http://semver.org/).
1616
* Add Node.js v20 to CI. (#2237)
1717
### Added
1818
* Added string tags to support class detection
19+
* Implemented `OffscreenCanvas.prototype.convertToBlob()` - Depends on global `Blob` support. (NodeJS 18+) (#1845)
1920
### Fixed
2021
* Fix a case of use-after-free. (#2229)
2122
* Fix usage of garbage value by filling the allocated memory entirely with zeros if it's not modified. (#2229)

lib/canvas.js

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77
*/
88

99
const bindings = require('./bindings')
10-
const Canvas = module.exports = bindings.Canvas
1110
const Context2d = require('./context2d')
1211
const PNGStream = require('./pngstream')
1312
const PDFStream = require('./pdfstream')
1413
const JPEGStream = require('./jpegstream')
1514
const FORMATS = ['image/png', 'image/jpeg']
1615
const util = require('util')
16+
const Canvas = bindings.Canvas
1717

1818
// TODO || is for Node.js pre-v6.6.0
1919
Canvas.prototype[util.inspect.custom || 'inspect'] = function () {
@@ -44,6 +44,31 @@ Canvas.prototype.createJPEGStream = function (options) {
4444
return new JPEGStream(this, options)
4545
}
4646

47+
/**
48+
* The OffscreenCanvas.convertToBlob() method creates a Blob object representing
49+
* the image contained in the canvas.
50+
*
51+
* @see https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas/convertToBlob
52+
* @since NodeJS v18.0.0
53+
*/
54+
Canvas.prototype.convertToBlob = async function (options = {}) {
55+
// If the user agent does not support the requested type, then it must create the file using the PNG format.
56+
// ref: https://html.spec.whatwg.org/multipage/canvas.html#a-serialisation-of-the-bitmap-as-a-file
57+
const type = options.type && FORMATS.includes(options.type)
58+
? options.type
59+
: 'image/png'
60+
61+
const quality = options.quality != null
62+
? { quality: options.quality }
63+
: undefined
64+
65+
return new Promise((resolve, reject) => {
66+
this.toBuffer((err, buf) => {
67+
err ? reject(err) : resolve(new Blob([buf], { type }))
68+
}, type, quality)
69+
})
70+
}
71+
4772
Canvas.prototype.toDataURL = function (a1, a2, a3) {
4873
// valid arg patterns (args -> [type, opts, fn]):
4974
// [] -> ['image/png', null, null]
@@ -111,3 +136,5 @@ Canvas.prototype.toDataURL = function (a1, a2, a3) {
111136
return `data:${type};base64,${this.toBuffer(type, opts).toString('base64')}`
112137
}
113138
}
139+
140+
module.exports = Canvas

0 commit comments

Comments
 (0)