77 */
88
99const bindings = require ( './bindings' )
10- const Canvas = module . exports = bindings . Canvas
1110const Context2d = require ( './context2d' )
1211const PNGStream = require ( './pngstream' )
1312const PDFStream = require ( './pdfstream' )
1413const JPEGStream = require ( './jpegstream' )
1514const FORMATS = [ 'image/png' , 'image/jpeg' ]
1615const util = require ( 'util' )
16+ const Canvas = bindings . Canvas
1717
1818// TODO || is for Node.js pre-v6.6.0
1919Canvas . 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+
4766Canvas . 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