generated from napi-rs/package-template
-
-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathnode-canvas.js
More file actions
379 lines (340 loc) · 11.6 KB
/
node-canvas.js
File metadata and controls
379 lines (340 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
'use strict'
const { Readable } = require('node:stream')
const {
createCanvas: _createCanvas,
Canvas,
CanvasElement,
SVGCanvas,
GlobalFonts,
Image,
ImageData,
Path2D,
DOMPoint,
DOMMatrix,
DOMRect,
loadImage,
PDFDocument,
SvgExportFlag,
} = require('./index.js')
// CanvasRenderingContext2D is not re-exported by index.js, grab from native bindings
const { CanvasRenderingContext2D } = require('./js-binding')
// node-canvas defaults JPEG quality to 0.75 across all paths.
// @napi-rs/canvas native default is 0.92 (matching Blink/Chrome).
const NODE_CANVAS_DEFAULT_QUALITY = 0.75
// ---------------------------------------------------------------------------
// Stream classes (node-canvas returns Node.js Readable streams)
// ---------------------------------------------------------------------------
class PNGStream extends Readable {
constructor(canvas, options) {
super()
this._canvas = canvas
this._options = options || {}
this._done = false
}
_read() {
if (this._done) return
this._done = true
this._canvas
.encode('png')
.then((buf) => {
this.push(buf)
this.push(null)
})
.catch((err) => {
this.destroy(err)
})
}
}
class JPEGStream extends Readable {
constructor(canvas, options) {
super()
this._canvas = canvas
const opts = options || {}
// node-canvas quality: 0-1 (default 0.75), encode() expects 0-100
this._quality = Math.round((opts.quality != null ? opts.quality : NODE_CANVAS_DEFAULT_QUALITY) * 100)
this._done = false
}
_read() {
if (this._done) return
this._done = true
this._canvas
.encode('jpeg', this._quality)
.then((buf) => {
this.push(buf)
this.push(null)
})
.catch((err) => {
this.destroy(err)
})
}
}
// ---------------------------------------------------------------------------
// Quality normalization helpers
// ---------------------------------------------------------------------------
const MIME_FORMAT_MAP = {
'image/png': 'png',
'image/jpeg': 'jpeg',
'image/webp': 'webp',
'image/avif': 'avif',
'image/gif': 'gif',
}
/**
* Extract quality from a node-canvas config object or number.
* Returns the raw 0-1 quality value, defaulting to NODE_CANVAS_DEFAULT_QUALITY
* for JPEG/WebP when not specified.
*
* @param {string} mime
* @param {number|object|undefined} configOrQuality
* @returns {number|undefined} 0-1 scale for JPEG/WebP, undefined for other mimes
*/
function _extractQuality(mime, configOrQuality) {
if (mime !== 'image/jpeg' && mime !== 'image/webp') return undefined
if (configOrQuality == null) return NODE_CANVAS_DEFAULT_QUALITY
if (typeof configOrQuality === 'number') return configOrQuality
if (typeof configOrQuality === 'object' && configOrQuality.quality != null) {
return configOrQuality.quality
}
return NODE_CANVAS_DEFAULT_QUALITY
}
// ---------------------------------------------------------------------------
// Compat methods added to each canvas instance created via this module
// ---------------------------------------------------------------------------
// Keep references to the original prototype methods
const _origToBuffer = CanvasElement.prototype.toBuffer
const _origToDataURL = CanvasElement.prototype.toDataURL
function _compatCreatePNGStream(options) {
return new PNGStream(this, options)
}
function _compatCreateJPEGStream(options) {
return new JPEGStream(this, options)
}
/**
* node-canvas compatible toBuffer:
* - toBuffer() → PNG (sync)
* - toBuffer('image/png', config?) → PNG (sync)
* - toBuffer('image/jpeg', config?) → JPEG (sync, quality 0-1)
* - toBuffer('raw') → raw pixel data (sync)
* - toBuffer(callback) → PNG (async)
* - toBuffer(callback, mime, config?) → specified format (async)
*/
function _compatToBuffer(mimeOrCallback, configOrQuality) {
// Callback form: toBuffer(callback) or toBuffer(callback, mime, config)
if (typeof mimeOrCallback === 'function') {
const callback = mimeOrCallback
const mime = typeof configOrQuality === 'string' ? configOrQuality : 'image/png'
const config = arguments[2]
if (mime === 'raw') {
let buf
try {
buf = this.data()
} catch (err) {
callback(err)
return
}
callback(null, buf)
return
}
const format = MIME_FORMAT_MAP[mime]
if (!format) {
callback(new TypeError(`Unsupported MIME type "${mime}". Supported: ${Object.keys(MIME_FORMAT_MAP).join(', ')}`))
return
}
const q = _extractQuality(mime, config)
this.encode(format, q != null ? Math.round(q * 100) : undefined).then(
(buf) => callback(null, buf),
(err) => callback(err),
)
return
}
// Sync: no args → PNG
if (mimeOrCallback === undefined) {
return _origToBuffer.call(this, 'image/png')
}
// Sync: raw pixel data
if (mimeOrCallback === 'raw') {
return this.data()
}
// Sync: extract quality (0-1) and scale to 0-100 for native toBuffer
const q = _extractQuality(mimeOrCallback, configOrQuality)
return _origToBuffer.call(this, mimeOrCallback, q != null ? Math.round(q * 100) : undefined)
}
/**
* node-canvas compatible toDataURL:
* - toDataURL() → PNG data URL (sync)
* - toDataURL('image/jpeg', quality) → JPEG data URL, quality 0-1 (sync)
* - toDataURL(callback) → PNG data URL (async)
* - toDataURL(mime, callback) → data URL (async)
* - toDataURL(mime, quality, callback) → data URL with quality (async)
*/
function _compatToDataURL(mimeOrCallback, qualityOrCallback) {
// toDataURL(callback)
if (typeof mimeOrCallback === 'function') {
this.toDataURLAsync('image/png').then(
(url) => mimeOrCallback(null, url),
(err) => mimeOrCallback(err),
)
return
}
// toDataURL(mime, callback)
if (typeof qualityOrCallback === 'function') {
this.toDataURLAsync(mimeOrCallback, _extractQuality(mimeOrCallback, undefined)).then(
(url) => qualityOrCallback(null, url),
(err) => qualityOrCallback(err),
)
return
}
// toDataURL(mime, quality, callback)
const cb = arguments[2]
if (typeof cb === 'function') {
// Native toDataURLAsync expects 0-1 (f64) — pass quality through as-is
const quality = _extractQuality(mimeOrCallback, qualityOrCallback)
this.toDataURLAsync(mimeOrCallback, quality).then(
(url) => cb(null, url),
(err) => cb(err),
)
return
}
// Sync form: native toDataURL expects 0-1 (f64) — pass quality through as-is
const quality = _extractQuality(mimeOrCallback, qualityOrCallback)
return _origToDataURL.call(this, mimeOrCallback, quality)
}
/**
* Attach node-canvas compatible methods to a CanvasElement instance.
*/
function _addCompatMethods(canvas) {
canvas.createPNGStream = _compatCreatePNGStream
canvas.createJPEGStream = _compatCreateJPEGStream
canvas.toBuffer = _compatToBuffer
canvas.toDataURL = _compatToDataURL
return canvas
}
// ---------------------------------------------------------------------------
// Public API: registerFont / deregisterAllFonts
// ---------------------------------------------------------------------------
// Track FontKeys from registerFont() so deregisterAllFonts() can remove
// only user-registered fonts (matching node-canvas behavior which leaves
// system fonts untouched).
const _registeredFontKeys = []
/**
* Register a font file with the specified font face properties.
* Compatible with node-canvas's registerFont(path, { family, weight?, style? }).
*
* Note: @napi-rs/canvas auto-detects weight and style from font file metadata
* (matching browser behavior). The weight and style properties in fontFace are
* accepted for API compatibility but the actual values are read from the font.
*
* @param {string} path Absolute path to the font file (.ttf, .otf, etc.)
* @param {{ family: string, weight?: string, style?: string }} fontFace
*/
function registerFont(path, fontFace) {
if (!fontFace || typeof fontFace.family !== 'string') {
throw new TypeError('registerFont requires a fontFace with a "family" property')
}
const key = GlobalFonts.registerFromPath(path, fontFace.family)
if (!key) {
throw new Error(`Failed to register font from "${path}" with family "${fontFace.family}"`)
}
_registeredFontKeys.push(key)
}
/**
* Deregister all fonts previously registered via registerFont().
* Compatible with node-canvas's deregisterAllFonts() which only removes
* user-registered fonts and leaves system fonts untouched.
*/
function deregisterAllFonts() {
if (_registeredFontKeys.length > 0) {
GlobalFonts.removeBatch(_registeredFontKeys)
_registeredFontKeys.length = 0
}
}
// ---------------------------------------------------------------------------
// Public API: createCanvas / createImageData
// ---------------------------------------------------------------------------
/**
* Create a new canvas instance with node-canvas compatible API.
*
* @param {number} width
* @param {number} height
* @param {'image'|'svg'} [type='image']
* @returns {Canvas}
*/
function createCanvas(width, height, type) {
if (type === 'svg') {
// SvgExportFlag enum requires a valid variant; NoPrettyXML (0x02) is the
// least impactful on rendering behavior (only affects XML whitespace).
return _createCanvas(width, height, SvgExportFlag.NoPrettyXML)
}
if (type === 'pdf') {
throw new Error(
'createCanvas with type "pdf" is not supported. Use the PDFDocument class from @napi-rs/canvas directly.',
)
}
if (type != null && type !== 'image') {
throw new TypeError(`createCanvas: unknown type "${type}". Supported types: "image", "svg".`)
}
return _addCompatMethods(_createCanvas(width, height))
}
/**
* Create an ImageData instance.
* Compatible with node-canvas's createImageData().
*
* @param {Uint8ClampedArray|number} dataOrWidth
* @param {number} widthOrHeight
* @param {number} [height]
* @returns {ImageData}
*/
function createImageData(dataOrWidth, widthOrHeight, height) {
if (typeof dataOrWidth === 'number') {
return new ImageData(dataOrWidth, widthOrHeight)
}
if (height != null) {
return new ImageData(dataOrWidth, widthOrHeight, height)
}
return new ImageData(dataOrWidth, widthOrHeight)
}
// ---------------------------------------------------------------------------
// Canvas constructor wrapper
// ---------------------------------------------------------------------------
// In node-canvas, `new Canvas(w, h)` and `createCanvas(w, h)` produce
// equivalent canvases. Wrap the native Canvas constructor so that
// `new Canvas(w, h)` also gets compat methods, without polluting the
// prototype (which would affect @napi-rs/canvas users who don't use
// this compat layer).
const CompatCanvas = new Proxy(Canvas, {
construct(target, args) {
const canvas = new target(...args)
if (canvas instanceof CanvasElement) {
return _addCompatMethods(canvas)
}
return canvas
},
})
// ---------------------------------------------------------------------------
// Exports (matches node-canvas export shape)
// ---------------------------------------------------------------------------
module.exports = {
// Factory functions
Canvas: CompatCanvas,
createCanvas,
createImageData,
loadImage,
registerFont,
deregisterAllFonts,
// Classes
Image,
ImageData,
CanvasRenderingContext2D,
Context2d: CanvasRenderingContext2D,
PNGStream,
JPEGStream,
Path2D,
// Geometry
DOMPoint,
DOMMatrix,
DOMRect,
// @napi-rs/canvas extras (available but not part of node-canvas)
GlobalFonts,
PDFDocument,
CanvasElement,
SVGCanvas,
}