|
7 | 7 | */
|
8 | 8 |
|
9 | 9 | const bindings = require('./bindings')
|
10 |
| -const Canvas = module.exports = bindings.Canvas |
11 | 10 | const Context2d = require('./context2d')
|
12 | 11 | const PNGStream = require('./pngstream')
|
13 | 12 | const PDFStream = require('./pdfstream')
|
14 | 13 | const JPEGStream = require('./jpegstream')
|
15 | 14 | const FORMATS = ['image/png', 'image/jpeg']
|
16 | 15 | const util = require('util')
|
| 16 | +const Canvas = bindings.Canvas |
17 | 17 |
|
18 | 18 | // TODO || is for Node.js pre-v6.6.0
|
19 | 19 | Canvas.prototype[util.inspect.custom || 'inspect'] = function () {
|
@@ -44,6 +44,31 @@ Canvas.prototype.createJPEGStream = function (options) {
|
44 | 44 | return new JPEGStream(this, options)
|
45 | 45 | }
|
46 | 46 |
|
| 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 | + |
47 | 72 | Canvas.prototype.toDataURL = function (a1, a2, a3) {
|
48 | 73 | // valid arg patterns (args -> [type, opts, fn]):
|
49 | 74 | // [] -> ['image/png', null, null]
|
@@ -111,3 +136,5 @@ Canvas.prototype.toDataURL = function (a1, a2, a3) {
|
111 | 136 | return `data:${type};base64,${this.toBuffer(type, opts).toString('base64')}`
|
112 | 137 | }
|
113 | 138 | }
|
| 139 | + |
| 140 | +module.exports = Canvas |
0 commit comments