Skip to content

Commit 03f2738

Browse files
committed
feat: implement OffscreenCanvas.convertToBlob
1 parent b3e7df3 commit 03f2738

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

lib/canvas.js

Lines changed: 22 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,25 @@ 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+
const type = options.type && FORMATS.includes(options.type)
56+
? options.type
57+
: 'image/png'
58+
59+
return new Promise((resolve, reject) => {
60+
this.toBuffer((err, buf) => {
61+
err ? reject(err) : resolve(new Blob([buf], { type }))
62+
}, type, options)
63+
})
64+
}
65+
4766
Canvas.prototype.toDataURL = function (a1, a2, a3) {
4867
// valid arg patterns (args -> [type, opts, fn]):
4968
// [] -> ['image/png', null, null]
@@ -111,3 +130,5 @@ Canvas.prototype.toDataURL = function (a1, a2, a3) {
111130
return `data:${type};base64,${this.toBuffer(type, opts).toString('base64')}`
112131
}
113132
}
133+
134+
module.exports = Canvas

0 commit comments

Comments
 (0)