@nexterm/canvas 0.0.0-stage → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts ADDED
@@ -0,0 +1,1467 @@
1
+ import { ReadableStream } from 'node:stream/web'
2
+
3
+ // Clear all type of caches in Skia
4
+ export function clearAllCache(): void
5
+
6
+ export type TextRenderer = 'portable' | 'system'
7
+
8
+ /**
9
+ * Selects how text is drawn.
10
+ *
11
+ * `'portable'` (the default) draws text the same way on every OS: FreeType,
12
+ * Skia's default text gamma, no LCD text and one font family table. Text gives
13
+ * the same pixels and TextMetrics on macOS, Linux and Windows when:
14
+ * - `ctx.font` names only fonts you registered (the default `10px sans-serif`
15
+ * and names like `Arial` use installed fonts, unless you registered a font
16
+ * under that name);
17
+ * - your registered fonts have every character you draw (a missing character
18
+ * comes from an installed font);
19
+ * - you set `ctx.lang` (for example `'en'`), because the default `'inherit'`
20
+ * follows the host language;
21
+ * - `FREETYPE_PROPERTIES` is not set.
22
+ * x64 and arm64 builds can still differ by 1 color level on some edge pixels.
23
+ *
24
+ * `'system'` draws text with each OS's own font renderer, as Chrome does:
25
+ * CoreText on macOS (Fontations for some color and variable fonts) with
26
+ * CoreText's installed fonts and fallback, Fontations on Linux, FreeType
27
+ * elsewhere; plus each OS's text gamma and contrast, LCD text on opaque macOS
28
+ * canvases, Chrome's per-OS font family settings and macOS metric rules.
29
+ *
30
+ * Applies to the whole process, worker threads included. Call it once at
31
+ * startup, before creating canvases. Setting the mode in use again changes
32
+ * nothing. Any other value throws a TypeError. Registered fonts keep their
33
+ * FontKey. A canvas created before the switch keeps its text gamma until its
34
+ * width or height is set. A `ctx.font` value set before the switch keeps its
35
+ * parsed form: sizes in `ex`/`ch`/... units and, on macOS, the
36
+ * BlinkMacSystemFont to system-ui rewrite. Set `ctx.font` again after the
37
+ * switch.
38
+ */
39
+ export function setTextRenderer(renderer: TextRenderer): void
40
+
41
+ /** The text renderer in use, set by {@link setTextRenderer}. */
42
+ export function getTextRenderer(): TextRenderer
43
+
44
+ interface CanvasRenderingContext2D
45
+ extends
46
+ CanvasCompositing,
47
+ CanvasDrawPath,
48
+ CanvasFillStrokeStyles,
49
+ CanvasFilters,
50
+ CanvasImageData,
51
+ CanvasImageSmoothing,
52
+ CanvasPath,
53
+ CanvasPathDrawingStyles,
54
+ CanvasRect,
55
+ CanvasSettings,
56
+ CanvasShadowStyles,
57
+ CanvasState,
58
+ CanvasText,
59
+ CanvasTextDrawingStyles,
60
+ CanvasTransform,
61
+ CanvasPDFAnnotations {}
62
+
63
+ interface CanvasState {
64
+ isContextLost(): boolean
65
+ reset(): void
66
+ restore(): void
67
+ save(): void
68
+ }
69
+ interface CanvasShadowStyles {
70
+ shadowBlur: number
71
+ shadowColor: string
72
+ shadowOffsetX: number
73
+ shadowOffsetY: number
74
+ }
75
+ type CanvasPixelFormat = 'float16' | 'unorm8'
76
+ interface CanvasToneMapping {
77
+ mode?: 'extended' | 'standard'
78
+ }
79
+ interface CanvasRenderingContext2DSettings {
80
+ alpha?: boolean
81
+ colorSpace?: PredefinedColorSpace
82
+ /** 'float16' stores half floats, as Chrome does; `canvas.data()` then gives them premultiplied, 8 bytes a pixel. */
83
+ colorType?: CanvasPixelFormat
84
+ desynchronized?: boolean
85
+ /** Not read by getContext() (as in Chrome); getContextAttributes() reports `{ mode: 'standard' }`. */
86
+ toneMapping?: CanvasToneMapping
87
+ willReadFrequently?: boolean
88
+ }
89
+ interface CanvasSettings {
90
+ getContextAttributes(): Required<CanvasRenderingContext2DSettings>
91
+ }
92
+
93
+ interface CanvasRect {
94
+ clearRect(x: number, y: number, w: number, h: number): void
95
+ fillRect(x: number, y: number, w: number, h: number): void
96
+ strokeRect(x: number, y: number, w: number, h: number): void
97
+ }
98
+
99
+ interface TextMetrics {
100
+ readonly actualBoundingBoxAscent: number
101
+ readonly actualBoundingBoxDescent: number
102
+ readonly actualBoundingBoxLeft: number
103
+ readonly actualBoundingBoxRight: number
104
+ readonly alphabeticBaseline: number
105
+ readonly emHeightAscent: number
106
+ readonly emHeightDescent: number
107
+ readonly fontBoundingBoxAscent: number
108
+ readonly fontBoundingBoxDescent: number
109
+ readonly hangingBaseline: number
110
+ readonly ideographicBaseline: number
111
+ readonly width: number
112
+ }
113
+
114
+ interface CanvasText {
115
+ fillText(text: string, x: number, y: number, maxWidth?: number): void
116
+ measureText(text: string): TextMetrics
117
+ strokeText(text: string, x: number, y: number, maxWidth?: number): void
118
+ }
119
+
120
+ type CanvasLineCap = 'butt' | 'round' | 'square'
121
+ type CanvasLineJoin = 'bevel' | 'miter' | 'round'
122
+
123
+ interface CanvasPathDrawingStyles {
124
+ lineCap: CanvasLineCap
125
+ lineDashOffset: number
126
+ lineJoin: CanvasLineJoin
127
+ lineWidth: number
128
+ miterLimit: number
129
+ getLineDash(): number[]
130
+ setLineDash(segments: number[]): void
131
+ }
132
+
133
+ interface CanvasPath {
134
+ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
135
+ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
136
+ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void
137
+ closePath(): void
138
+ ellipse(
139
+ x: number,
140
+ y: number,
141
+ radiusX: number,
142
+ radiusY: number,
143
+ rotation: number,
144
+ startAngle: number,
145
+ endAngle: number,
146
+ counterclockwise?: boolean,
147
+ ): void
148
+ lineTo(x: number, y: number): void
149
+ moveTo(x: number, y: number): void
150
+ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
151
+ rect(x: number, y: number, w: number, h: number): void
152
+ roundRect(
153
+ x: number,
154
+ y: number,
155
+ w: number,
156
+ h: number,
157
+ radii?: number | DOMPointInit | Iterable<number | DOMPointInit>,
158
+ ): void
159
+ }
160
+
161
+ type ImageSmoothingQuality = 'high' | 'low' | 'medium'
162
+
163
+ interface CanvasImageSmoothing {
164
+ imageSmoothingEnabled: boolean
165
+ imageSmoothingQuality: ImageSmoothingQuality
166
+ }
167
+
168
+ interface CanvasTransform {
169
+ resetTransform(): void
170
+ rotate(angle: number): void
171
+ scale(x: number, y: number): void
172
+ setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void
173
+ /** Missing members default to the identity; `a` and `m11` (and so on) must agree when both are given. */
174
+ setTransform(
175
+ transform?: Partial<DOMMatrixInit> & {
176
+ m11?: number
177
+ m12?: number
178
+ m21?: number
179
+ m22?: number
180
+ m41?: number
181
+ m42?: number
182
+ },
183
+ ): void
184
+ transform(a: number, b: number, c: number, d: number, e: number, f: number): void
185
+ translate(x: number, y: number): void
186
+ }
187
+
188
+ interface CanvasPDFAnnotations {
189
+ /**
190
+ * Create a clickable URL link annotation in a PDF document.
191
+ * This is only effective when used with PDF documents.
192
+ * @param left - Left coordinate of the link rectangle
193
+ * @param top - Top coordinate of the link rectangle
194
+ * @param right - Right coordinate of the link rectangle
195
+ * @param bottom - Bottom coordinate of the link rectangle
196
+ * @param url - The URL to link to
197
+ */
198
+ annotateLinkUrl(left: number, top: number, right: number, bottom: number, url: string): void
199
+
200
+ /**
201
+ * Create a named destination at a specific point in a PDF document.
202
+ * This destination can be used as a target for internal links.
203
+ * @param x - X coordinate of the destination point
204
+ * @param y - Y coordinate of the destination point
205
+ * @param name - Name identifier for the destination
206
+ */
207
+ annotateNamedDestination(x: number, y: number, name: string): void
208
+
209
+ /**
210
+ * Create a link to a named destination within the PDF document.
211
+ * This is only effective when used with PDF documents.
212
+ * @param left - Left coordinate of the link rectangle
213
+ * @param top - Top coordinate of the link rectangle
214
+ * @param right - Right coordinate of the link rectangle
215
+ * @param bottom - Bottom coordinate of the link rectangle
216
+ * @param name - Name of the destination to link to
217
+ */
218
+ annotateLinkToDestination(left: number, top: number, right: number, bottom: number, name: string): void
219
+ }
220
+
221
+ type PredefinedColorSpace = 'display-p3' | 'srgb'
222
+ /** 'rgba-float16' throws a NotSupportedError on a runtime without Float16Array (Node 22). */
223
+ type ImageDataPixelFormat = 'rgba-unorm8' | 'rgba-float16' | 'rgba-float32'
224
+ /** Float16Array, where the TypeScript lib has it. */
225
+ type ImageDataFloat16Array = typeof globalThis extends { Float16Array: { prototype: infer T } } ? T : never
226
+ type ImageDataArray = Uint8ClampedArray | ImageDataFloat16Array | Float32Array
227
+
228
+ interface ImageDataSettings {
229
+ colorSpace?: PredefinedColorSpace
230
+ pixelFormat?: ImageDataPixelFormat
231
+ }
232
+ interface CanvasImageData {
233
+ createImageData(sw: number, sh: number, settings?: ImageDataSettings & { pixelFormat?: 'rgba-unorm8' }): ImageData
234
+ createImageData(
235
+ sw: number,
236
+ sh: number,
237
+ settings: ImageDataSettings & { pixelFormat: 'rgba-float16' },
238
+ ): ImageData<ImageDataFloat16Array>
239
+ createImageData(
240
+ sw: number,
241
+ sh: number,
242
+ settings: ImageDataSettings & { pixelFormat: 'rgba-float32' },
243
+ ): ImageData<Float32Array>
244
+ createImageData(sw: number, sh: number, settings?: ImageDataSettings): ImageData<ImageDataArray>
245
+ createImageData<T extends ImageDataArray>(imagedata: ImageData<T>): ImageData<T>
246
+ getImageData(
247
+ sx: number,
248
+ sy: number,
249
+ sw: number,
250
+ sh: number,
251
+ settings?: ImageDataSettings & { pixelFormat?: 'rgba-unorm8' },
252
+ ): ImageData
253
+ getImageData(
254
+ sx: number,
255
+ sy: number,
256
+ sw: number,
257
+ sh: number,
258
+ settings: ImageDataSettings & { pixelFormat: 'rgba-float16' },
259
+ ): ImageData<ImageDataFloat16Array>
260
+ getImageData(
261
+ sx: number,
262
+ sy: number,
263
+ sw: number,
264
+ sh: number,
265
+ settings: ImageDataSettings & { pixelFormat: 'rgba-float32' },
266
+ ): ImageData<Float32Array>
267
+ getImageData(sx: number, sy: number, sw: number, sh: number, settings?: ImageDataSettings): ImageData<ImageDataArray>
268
+ putImageData(imagedata: ImageData<ImageDataArray>, dx: number, dy: number): void
269
+ putImageData(
270
+ imagedata: ImageData<ImageDataArray>,
271
+ dx: number,
272
+ dy: number,
273
+ dirtyX: number,
274
+ dirtyY: number,
275
+ dirtyWidth: number,
276
+ dirtyHeight: number,
277
+ ): void
278
+ }
279
+
280
+ type CanvasDirection = 'inherit' | 'ltr' | 'rtl'
281
+ type CanvasFontKerning = 'auto' | 'none' | 'normal'
282
+ type CanvasFontStretch =
283
+ | 'condensed'
284
+ | 'expanded'
285
+ | 'extra-condensed'
286
+ | 'extra-expanded'
287
+ | 'normal'
288
+ | 'semi-condensed'
289
+ | 'semi-expanded'
290
+ | 'ultra-condensed'
291
+ | 'ultra-expanded'
292
+ type CanvasFontVariantCaps =
293
+ 'all-petite-caps' | 'all-small-caps' | 'normal' | 'petite-caps' | 'small-caps' | 'titling-caps' | 'unicase'
294
+ type CanvasTextAlign = 'center' | 'end' | 'left' | 'right' | 'start'
295
+ type CanvasTextBaseline = 'alphabetic' | 'bottom' | 'hanging' | 'ideographic' | 'middle' | 'top'
296
+ type CanvasTextRendering = 'auto' | 'geometricPrecision' | 'optimizeLegibility' | 'optimizeSpeed'
297
+
298
+ interface CanvasTextDrawingStyles {
299
+ direction: CanvasDirection
300
+ font: string
301
+ fontKerning: CanvasFontKerning
302
+ fontStretch: CanvasFontStretch
303
+ fontVariantCaps: CanvasFontVariantCaps
304
+ letterSpacing: string
305
+ textAlign: CanvasTextAlign
306
+ textBaseline: CanvasTextBaseline
307
+ textRendering: CanvasTextRendering
308
+ wordSpacing: string
309
+ lang: string
310
+ }
311
+
312
+ interface CanvasFilters {
313
+ filter: string
314
+ }
315
+
316
+ interface CanvasFillStrokeStyles {
317
+ fillStyle: string | CanvasGradient | CanvasPattern
318
+ strokeStyle: string | CanvasGradient | CanvasPattern
319
+ createConicGradient(startAngle: number, x: number, y: number): CanvasGradient
320
+ createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient
321
+ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient
322
+ }
323
+
324
+ type CanvasFillRule = 'evenodd' | 'nonzero'
325
+
326
+ interface CanvasDrawPath {
327
+ beginPath(): void
328
+ clip(fillRule?: CanvasFillRule): void
329
+ clip(path: Path2D, fillRule?: CanvasFillRule): void
330
+ fill(fillRule?: CanvasFillRule): void
331
+ fill(path: Path2D, fillRule?: CanvasFillRule): void
332
+ isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean
333
+ isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean
334
+ isPointInStroke(x: number, y: number): boolean
335
+ isPointInStroke(path: Path2D, x: number, y: number): boolean
336
+ stroke(): void
337
+ stroke(path: Path2D): void
338
+ }
339
+
340
+ type GlobalCompositeOperation =
341
+ | 'color'
342
+ | 'color-burn'
343
+ | 'color-dodge'
344
+ | 'copy'
345
+ | 'darken'
346
+ | 'destination-atop'
347
+ | 'destination-in'
348
+ | 'destination-out'
349
+ | 'destination-over'
350
+ | 'difference'
351
+ | 'exclusion'
352
+ | 'hard-light'
353
+ | 'hue'
354
+ | 'lighten'
355
+ | 'lighter'
356
+ | 'luminosity'
357
+ | 'multiply'
358
+ | 'overlay'
359
+ | 'saturation'
360
+ | 'screen'
361
+ | 'soft-light'
362
+ | 'source-atop'
363
+ | 'source-in'
364
+ | 'source-out'
365
+ | 'source-over'
366
+ | 'xor'
367
+
368
+ interface CanvasCompositing {
369
+ globalAlpha: number
370
+ globalCompositeOperation: GlobalCompositeOperation
371
+ }
372
+
373
+ interface DOMPointInit {
374
+ w?: number
375
+ x?: number
376
+ y?: number
377
+ z?: number
378
+ }
379
+ interface CanvasPattern {
380
+ /** Missing members default to the identity; `a` and `m11` (and so on) must agree when both are given. */
381
+ setTransform(
382
+ transform?: Partial<DOMMatrix2DInit> & {
383
+ m11?: number
384
+ m12?: number
385
+ m21?: number
386
+ m22?: number
387
+ m41?: number
388
+ m42?: number
389
+ },
390
+ ): void
391
+ }
392
+
393
+ interface CanvasGradient {
394
+ addColorStop(offset: number, color: string): void
395
+ }
396
+
397
+ interface DOMRectInit {
398
+ height?: number
399
+ width?: number
400
+ x?: number
401
+ y?: number
402
+ }
403
+
404
+ interface DOMMatrixInit extends DOMMatrix2DInit {
405
+ is2D?: boolean
406
+ m13?: number
407
+ m14?: number
408
+ m23?: number
409
+ m24?: number
410
+ m31?: number
411
+ m32?: number
412
+ m33?: number
413
+ m34?: number
414
+ m43?: number
415
+ m44?: number
416
+ }
417
+
418
+ // ----------- added types
419
+
420
+ export interface DOMMatrix2DInit {
421
+ a: number
422
+ b: number
423
+ c: number
424
+ d: number
425
+ e: number
426
+ f: number
427
+ }
428
+
429
+ interface DOMMatrixReadOnly {
430
+ readonly a: number
431
+ readonly b: number
432
+ readonly c: number
433
+ readonly d: number
434
+ readonly e: number
435
+ readonly f: number
436
+ readonly is2D: boolean
437
+ readonly isIdentity: boolean
438
+ readonly m11: number
439
+ readonly m12: number
440
+ readonly m13: number
441
+ readonly m14: number
442
+ readonly m21: number
443
+ readonly m22: number
444
+ readonly m23: number
445
+ readonly m24: number
446
+ readonly m31: number
447
+ readonly m32: number
448
+ readonly m33: number
449
+ readonly m34: number
450
+ readonly m41: number
451
+ readonly m42: number
452
+ readonly m43: number
453
+ readonly m44: number
454
+ flipX(): DOMMatrix
455
+ flipY(): DOMMatrix
456
+ inverse(): DOMMatrix
457
+ multiply(other?: DOMMatrixInit): DOMMatrix
458
+ rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix
459
+ rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix
460
+ rotateFromVector(x?: number, y?: number): DOMMatrix
461
+ scale(
462
+ scaleX?: number,
463
+ scaleY?: number,
464
+ scaleZ?: number,
465
+ originX?: number,
466
+ originY?: number,
467
+ originZ?: number,
468
+ ): DOMMatrix
469
+ scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix
470
+ skewX(sx?: number): DOMMatrix
471
+ skewY(sy?: number): DOMMatrix
472
+ toFloat32Array(): Float32Array
473
+ toFloat64Array(): Float64Array
474
+ transformPoint(point?: DOMPointInit): DOMPoint
475
+ translate(tx?: number, ty?: number, tz?: number): DOMMatrix
476
+ toString(): string
477
+ }
478
+
479
+ export interface DOMMatrix extends DOMMatrixReadOnly {
480
+ a: number
481
+ b: number
482
+ c: number
483
+ d: number
484
+ e: number
485
+ f: number
486
+ m11: number
487
+ m12: number
488
+ m13: number
489
+ m14: number
490
+ m21: number
491
+ m22: number
492
+ m23: number
493
+ m24: number
494
+ m31: number
495
+ m32: number
496
+ m33: number
497
+ m34: number
498
+ m41: number
499
+ m42: number
500
+ m43: number
501
+ m44: number
502
+ invertSelf(): DOMMatrix
503
+ multiplySelf(other?: DOMMatrixInit): DOMMatrix
504
+ preMultiplySelf(other?: DOMMatrixInit): DOMMatrix
505
+ rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix
506
+ rotateFromVectorSelf(x?: number, y?: number): DOMMatrix
507
+ rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix
508
+ scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix
509
+ scaleSelf(
510
+ scaleX?: number,
511
+ scaleY?: number,
512
+ scaleZ?: number,
513
+ originX?: number,
514
+ originY?: number,
515
+ originZ?: number,
516
+ ): DOMMatrix
517
+ setMatrixValue(transformList: string): DOMMatrix
518
+ skewXSelf(sx?: number): DOMMatrix
519
+ skewYSelf(sy?: number): DOMMatrix
520
+ translateSelf(tx?: number, ty?: number, tz?: number): DOMMatrix
521
+ toJSON(): { [K in OmitNeverOfMatrix]: DOMMatrix[K] }
522
+ }
523
+
524
+ type OmitMatrixMethod = { [K in keyof DOMMatrix]: DOMMatrix[K] extends (...args: any[]) => any ? never : K }
525
+
526
+ type OmitNeverOfMatrix = OmitMatrixMethod[keyof OmitMatrixMethod]
527
+
528
+ export const DOMMatrix: {
529
+ prototype: DOMMatrix
530
+ new (init?: string | number[]): DOMMatrix
531
+ fromFloat32Array(array32: Float32Array): DOMMatrix
532
+ fromFloat64Array(array64: Float64Array): DOMMatrix
533
+ fromMatrix(other?: DOMMatrixInit): DOMMatrix
534
+ }
535
+
536
+ interface DOMRectReadOnly {
537
+ readonly bottom: number
538
+ readonly height: number
539
+ readonly left: number
540
+ readonly right: number
541
+ readonly top: number
542
+ readonly width: number
543
+ readonly x: number
544
+ readonly y: number
545
+ }
546
+
547
+ export interface DOMRect extends DOMRectReadOnly {
548
+ height: number
549
+ width: number
550
+ x: number
551
+ y: number
552
+ toJSON(): Omit<this, 'toJSON' | 'fromRect'>
553
+ }
554
+
555
+ export const DOMRect: {
556
+ prototype: DOMRect
557
+ new (x?: number, y?: number, width?: number, height?: number): DOMRect
558
+ fromRect(other?: DOMRectInit): DOMRect
559
+ }
560
+
561
+ interface DOMPointReadOnly {
562
+ readonly w: number
563
+ readonly x: number
564
+ readonly y: number
565
+ readonly z: number
566
+ matrixTransform(matrix?: DOMMatrixInit): DOMPoint
567
+ }
568
+
569
+ export interface DOMPoint extends DOMPointReadOnly {
570
+ w: number
571
+ x: number
572
+ y: number
573
+ z: number
574
+ toJSON(): Omit<DOMPoint, 'matrixTransform' | 'toJSON'>
575
+ }
576
+
577
+ export const DOMPoint: {
578
+ prototype: DOMPoint
579
+ new (x?: number, y?: number, z?: number, w?: number): DOMPoint
580
+ fromPoint(other?: DOMPointInit): DOMPoint
581
+ }
582
+
583
+ export class ImageData<T extends ImageDataArray = Uint8ClampedArray> {
584
+ /**
585
+ * Returns the one-dimensional array containing the data in RGBA order: integers in the range 0 to 255 for
586
+ * 'rgba-unorm8', unpremultiplied floats for 'rgba-float16' and 'rgba-float32'.
587
+ */
588
+ readonly data: T
589
+ /**
590
+ * Returns the actual dimensions of the data in the ImageData object, in pixels.
591
+ */
592
+ readonly height: number
593
+ /**
594
+ * Returns the actual dimensions of the data in the ImageData object, in pixels.
595
+ */
596
+ readonly width: number
597
+ readonly colorSpace: PredefinedColorSpace
598
+ readonly pixelFormat: ImageDataPixelFormat
599
+
600
+ /** Pass the data type for a float pixelFormat: `new ImageData<Float32Array>(w, h, { pixelFormat: 'rgba-float32' })`. */
601
+ constructor(sw: number, sh: number, settings?: ImageDataSettings)
602
+ /** The pixelFormat must match the data type. */
603
+ constructor(data: T, sw: number, sh?: number, settings?: ImageDataSettings)
604
+ }
605
+
606
+ export class Image {
607
+ constructor()
608
+ // attrs only affects SVG
609
+ constructor(width: number, height: number, attrs?: { colorSpace?: ColorSpace })
610
+ width: number
611
+ height: number
612
+ readonly naturalWidth: number
613
+ readonly naturalHeight: number
614
+ readonly complete: boolean
615
+ readonly currentSrc: string | null
616
+ alt: string
617
+ // the src can be a Uint8Array or a string
618
+ // if it's a string, it can be a file path, a data URL, a remote URL, or a SVG string
619
+ src: Uint8Array | string
620
+ onload?(): void
621
+ /** Called with an Event of type 'error', as in browsers. */
622
+ onerror?(event: Event): void
623
+ /** Rejects with an EncodingError DOMException when the image cannot be decoded. */
624
+ decode(): Promise<void>
625
+ }
626
+
627
+ export class Path2D {
628
+ constructor(path?: Path2D | string)
629
+
630
+ /** Missing members default to the identity; `a` and `m11` (and so on) must agree when both are given. */
631
+ addPath(
632
+ path: Path2D,
633
+ transform?: Partial<DOMMatrix2DInit> & {
634
+ m11?: number
635
+ m12?: number
636
+ m21?: number
637
+ m22?: number
638
+ m41?: number
639
+ m42?: number
640
+ },
641
+ ): void
642
+ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void
643
+ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
644
+ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void
645
+ closePath(): void
646
+ ellipse(
647
+ x: number,
648
+ y: number,
649
+ radiusX: number,
650
+ radiusY: number,
651
+ rotation: number,
652
+ startAngle: number,
653
+ endAngle: number,
654
+ anticlockwise?: boolean,
655
+ ): void
656
+ lineTo(x: number, y: number): void
657
+ moveTo(x: number, y: number): void
658
+ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
659
+ rect(x: number, y: number, w: number, h: number): void
660
+ roundRect(
661
+ x: number,
662
+ y: number,
663
+ w: number,
664
+ h: number,
665
+ radii?: number | DOMPointInit | Iterable<number | DOMPointInit>,
666
+ ): void
667
+
668
+ // PathKit methods
669
+ op(path: Path2D, operation: PathOp): Path2D
670
+ toSVGString(): string
671
+ getFillType(): FillType
672
+ getFillTypeString(): string
673
+ setFillType(type: FillType): void
674
+ simplify(): Path2D
675
+ asWinding(): Path2D
676
+ stroke(stroke?: StrokeOptions): Path2D
677
+ transform(transform: DOMMatrix2DInit): Path2D
678
+ getBounds(): [left: number, top: number, right: number, bottom: number]
679
+ computeTightBounds(): [left: number, top: number, right: number, bottom: number]
680
+ trim(start: number, end: number, isComplement?: boolean): Path2D
681
+ dash(on: number, off: number, phase: number): Path2D
682
+ round(radius: number): Path2D
683
+ equals(path: Path2D): boolean
684
+ }
685
+
686
+ export interface StrokeOptions {
687
+ width?: number
688
+ miterLimit?: number
689
+ cap?: StrokeCap
690
+ join?: StrokeJoin
691
+ }
692
+
693
+ export interface SKRSContext2D extends CanvasRenderingContext2D {
694
+ readonly canvas: Canvas
695
+ /**
696
+ * @param startAngle The angle at which to begin the gradient, in radians. Angle measurements start vertically above the centre and move around clockwise.
697
+ * @param x The x-axis coordinate of the centre of the gradient.
698
+ * @param y The y-axis coordinate of the centre of the gradient.
699
+ */
700
+ createConicGradient(startAngle: number, x: number, y: number): CanvasGradient
701
+ drawImage(image: Image | Canvas | SvgCanvas, dx: number, dy: number): void
702
+ drawImage(image: Image | Canvas | SvgCanvas, dx: number, dy: number, dw: number, dh: number): void
703
+ drawImage(
704
+ image: Image | Canvas | SvgCanvas,
705
+ sx: number,
706
+ sy: number,
707
+ sw: number,
708
+ sh: number,
709
+ dx: number,
710
+ dy: number,
711
+ dw: number,
712
+ dh: number,
713
+ ): void
714
+ /**
715
+ * Draw another canvas, preserving vector graphics when possible.
716
+ * When the source canvas has recorded operations, this method preserves the
717
+ * SkPicture representation without rasterization, which can be faster than
718
+ * drawImage. Falls back to bitmap rendering if no picture is available.
719
+ */
720
+ drawCanvas(canvas: Canvas, dx: number, dy: number): void
721
+ drawCanvas(canvas: Canvas, dx: number, dy: number, dWidth: number, dHeight: number): void
722
+ drawCanvas(
723
+ canvas: Canvas,
724
+ sx: number,
725
+ sy: number,
726
+ sWidth: number,
727
+ sHeight: number,
728
+ dx: number,
729
+ dy: number,
730
+ dWidth: number,
731
+ dHeight: number,
732
+ ): void
733
+ /** null when `image` is an Image with no src or one that is still loading. */
734
+ createPattern(
735
+ image: Image | ImageData<ImageDataArray> | Canvas | SvgCanvas,
736
+ repeat: 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat' | '' | null,
737
+ ): CanvasPattern | null
738
+ getContextAttributes(): Required<CanvasRenderingContext2DSettings>
739
+ getTransform(): DOMMatrix
740
+
741
+ /**
742
+ * Non-standard (`node-canvas` extension): controls raster antialiasing for
743
+ * subsequent drawing operations. Default `"default"`.
744
+ *
745
+ * - `"none"`: disables antialiasing on raster shapes, clips, text, and bitmap
746
+ * image borders (vector SVG/PDF output and SVG `Image` content are unaffected).
747
+ * - `"default" | "gray" | "subpixel"`: keeps antialiasing enabled.
748
+ *
749
+ * Invalid values are silently ignored.
750
+ */
751
+ antialias: 'default' | 'none' | 'gray' | 'subpixel'
752
+
753
+ letterSpacing: string
754
+ wordSpacing: string
755
+ /**
756
+ * Non-standard: Chrome's CanvasRenderingContext2D has no such attribute.
757
+ * Behaves like the CSS `font-variation-settings` property in Chrome.
758
+ * Invalid values are ignored. Default `"normal"`.
759
+ * @experimental
760
+ */
761
+ fontVariationSettings: string
762
+ /**
763
+ * Non-standard: Chrome's CanvasRenderingContext2D has no such attribute.
764
+ * Behaves like the CSS `font-feature-settings` property in Chrome.
765
+ * Invalid values are ignored. Default `"normal"`.
766
+ * @experimental
767
+ */
768
+ fontFeatureSettings: string
769
+ /**
770
+ * Non-standard: Chrome's CanvasRenderingContext2D has no such attribute.
771
+ * Behaves like the CSS `font-variant-ligatures` property in Chrome.
772
+ * Invalid values are ignored. Default `"normal"`.
773
+ * @experimental
774
+ */
775
+ fontVariantLigatures: string
776
+ /**
777
+ * Non-standard: Chrome's CanvasRenderingContext2D has no such attribute.
778
+ * Behaves like the CSS `font-variant-numeric` property in Chrome.
779
+ * Invalid values are ignored. Default `"normal"`.
780
+ * @experimental
781
+ */
782
+ fontVariantNumeric: string
783
+ /**
784
+ * Non-standard: Chrome's CanvasRenderingContext2D has no such attribute.
785
+ * Behaves like the CSS `font-variant-position` property in Chrome.
786
+ * Invalid values are ignored. Default `"normal"`.
787
+ * @experimental
788
+ */
789
+ fontVariantPosition: 'normal' | 'sub' | 'super'
790
+ /**
791
+ * Non-standard: Chrome's CanvasRenderingContext2D has no such attribute.
792
+ * Behaves like the CSS `font-size-adjust` property in Chrome.
793
+ * Invalid values are ignored. Default `"none"`.
794
+ * @experimental
795
+ */
796
+ fontSizeAdjust: string
797
+ /**
798
+ * Non-standard: Chrome's CanvasRenderingContext2D has no such attribute.
799
+ * Behaves like the CSS `font-optical-sizing` property in Chrome.
800
+ * Invalid values are ignored. Default `"auto"`.
801
+ * @experimental
802
+ */
803
+ fontOpticalSizing: 'auto' | 'none'
804
+ }
805
+
806
+ export type ColorSpace = 'srgb' | 'display-p3'
807
+
808
+ export interface ContextAttributes extends CanvasRenderingContext2DSettings {}
809
+
810
+ export interface SvgCanvas {
811
+ width: number
812
+ height: number
813
+ /**
814
+ * Returns null for an id other than '2d', as browsers do for an unsupported id.
815
+ * Declared before the '2d' overload, so `ReturnType` still gives the context.
816
+ */
817
+ getContext<T extends string>(
818
+ contextType: T extends '2d' ? never : T,
819
+ contextAttributes?: ContextAttributes,
820
+ ): SKRSContext2D | null
821
+ getContext(contextType: '2d', contextAttributes?: ContextAttributes): SKRSContext2D
822
+
823
+ getContent(): Buffer
824
+ }
825
+
826
+ export interface AvifConfig {
827
+ /**
828
+ * 0-100 scale, 100 is the best quality. 100 with 4:4:4 (the default) is
829
+ * lossless: R, G and B are coded as they are (CICP matrix 0, identity).
830
+ * Below 100, or with chroma subsampling, the pixels are lossy BT.601 YUV.
831
+ * Default 80.
832
+ */
833
+ quality?: number
834
+ /** 0-100 scale. Default 100 when `quality` is 100 (lossless alpha), else 90. */
835
+ alphaQuality?: number
836
+ /**
837
+ * aom encoder speed from 0 (slowest, smallest file) to 10 (fastest);
838
+ * larger values are 10. Default 5.
839
+ */
840
+ speed?: number
841
+ /** How many threads to use: 0 or unset is one per CPU core; at most 64. */
842
+ threads?: number
843
+ /** set to '4:2:0' to use chroma subsampling, default '4:4:4' */
844
+ chromaSubsampling?: ChromaSubsampling
845
+ }
846
+
847
+ /**
848
+ * Metadata that `toBuffer`, `encode` and `encodeSync` write into PNG and JPEG
849
+ * output. It goes in the same options object as the other options. WebP, AVIF
850
+ * and GIF output ignore it. `toDataURL`, `toDataURLAsync`, `toBlob`,
851
+ * `convertToBlob`, `encodeStream` and `savePng` never write it.
852
+ *
853
+ * Nothing is converted, as in node-canvas: a member counts only when it is a
854
+ * number (`resolution`) or a string (the text members). Any other value is
855
+ * ignored. U+0000 is removed from text, and text that is then empty writes
856
+ * nothing. In JPEG, the XMP text must fit in one 64 KB segment (about 65000
857
+ * bytes of UTF-8 in all) and `comment` in 65533 UTF-8 bytes; more is a
858
+ * RangeError. PNG text has no such limit.
859
+ */
860
+ export interface ImageMetadata {
861
+ /**
862
+ * Pixels per inch for both axes, as node-canvas's `PngConfig.resolution`.
863
+ * The fraction is dropped (300.9 is 300). A value below 1, NaN and the
864
+ * infinities write nothing.
865
+ * - PNG: a `pHYs` chunk of `Math.round(ppi * 39.3701)` pixels per metre (the
866
+ * bytes node-canvas writes), at most 2147483647.
867
+ * - JPEG: the JFIF density in dots per inch, at most 65535.
868
+ */
869
+ resolution?: number
870
+ /** PNG `Title` text chunk; JPEG XMP `dc:title`. */
871
+ title?: string
872
+ /** PNG `Author` text chunk; JPEG XMP `dc:creator`. */
873
+ author?: string
874
+ /** PNG `Description` text chunk; JPEG XMP `dc:description`. */
875
+ description?: string
876
+ /** PNG `Copyright` text chunk; JPEG XMP `dc:rights`. */
877
+ copyright?: string
878
+ /** PNG `Software` text chunk; JPEG XMP `xmp:CreatorTool`. */
879
+ software?: string
880
+ /** PNG `Comment` text chunk; JPEG `COM` segment. */
881
+ comment?: string
882
+ }
883
+
884
+ /** The object form of `encode('jpeg')` and `encodeSync('jpeg')`: a quality and metadata. */
885
+ export interface JpegEncodeOptions extends ImageMetadata {
886
+ /** 0-100; a larger value is 100. Default 92. */
887
+ quality?: number
888
+ }
889
+
890
+ /**
891
+ * libpng row filter flags for {@link PngEncodeOptions.filters}, combinable with `|`.
892
+ * Use `None` (`0x08`) to disable row filtering; default is `All` (`0xF8`).
893
+ */
894
+ export enum PngFilter {
895
+ None = 0x08,
896
+ Sub = 0x10,
897
+ Up = 0x20,
898
+ Avg = 0x40,
899
+ Paeth = 0x80,
900
+ All = 0xf8,
901
+ }
902
+
903
+ export interface PngEncodeOptions extends ImageMetadata {
904
+ /**
905
+ * zlib compression level, an integer from 0 (uncompressed, fastest) to 9 (smallest).
906
+ * Out-of-range, fractional and non-number values use the default (6).
907
+ */
908
+ compressionLevel?: number
909
+ /**
910
+ * libpng row filter bitmask (see {@link PngFilter}): a non-zero OR of
911
+ * `0x08` (none), `0x10` (sub), `0x20` (up), `0x40` (average), `0x80` (Paeth).
912
+ * Any other value (including `0`) uses the default (`0xF8`, all filters).
913
+ */
914
+ filters?: number
915
+ }
916
+
917
+ /** GIF encoding configuration for single-frame encoding */
918
+ export interface GifConfig {
919
+ /**
920
+ * Quality for NeuQuant color quantization (1-30, lower = slower but better quality)
921
+ * @default 10
922
+ */
923
+ quality?: number
924
+ }
925
+
926
+ /** Configuration for the GIF encoder (animated GIFs) */
927
+ export interface GifEncoderConfig {
928
+ /**
929
+ * Loop count: 0 = infinite loop, positive number = finite loops
930
+ * @default 0 (infinite)
931
+ */
932
+ repeat?: number
933
+ /**
934
+ * Quality for NeuQuant color quantization (1-30, lower = slower but better quality)
935
+ * @default 10
936
+ */
937
+ quality?: number
938
+ }
939
+
940
+ /** Configuration for individual GIF frames */
941
+ export interface GifFrameConfig {
942
+ /**
943
+ * Frame delay in milliseconds
944
+ * @default 100
945
+ */
946
+ delay?: number
947
+ /** Disposal method for this frame */
948
+ disposal?: GifDisposal
949
+ /** Transparent color index (0-255), if the frame has transparency */
950
+ transparent?: number
951
+ /** X offset of this frame within the canvas */
952
+ left?: number
953
+ /** Y offset of this frame within the canvas */
954
+ top?: number
955
+ }
956
+
957
+ /** GIF frame disposal method */
958
+ export enum GifDisposal {
959
+ /** Keep the frame visible (default) */
960
+ Keep = 0,
961
+ /** Clear the frame area to the background color */
962
+ Background = 1,
963
+ /** Restore to the previous frame */
964
+ Previous = 2,
965
+ }
966
+
967
+ /**
968
+ * GIF Encoder for creating animated GIFs.
969
+ * Implements `Disposable` interface for use with the `using` keyword (ES2024).
970
+ *
971
+ * @example
972
+ * ```typescript
973
+ * // Basic usage
974
+ * const encoder = new GifEncoder(100, 100, { repeat: 0, quality: 10 });
975
+ * encoder.addFrame(rgbaData, 100, 100, { delay: 100 });
976
+ * encoder.addFrame(rgbaData2, 100, 100, { delay: 100 });
977
+ * const buffer = encoder.finish();
978
+ *
979
+ * // With `using` keyword (automatic cleanup)
980
+ * {
981
+ * using encoder = new GifEncoder(100, 100);
982
+ * encoder.addFrame(frame1, 100, 100, { delay: 100 });
983
+ * const buffer = encoder.finish();
984
+ * } // encoder automatically disposed
985
+ * ```
986
+ */
987
+ export class GifEncoder implements Disposable {
988
+ /**
989
+ * Create a new GIF encoder with the specified dimensions
990
+ * @param width - Width of the GIF canvas in pixels
991
+ * @param height - Height of the GIF canvas in pixels
992
+ * @param config - Optional encoder configuration
993
+ */
994
+ constructor(width: number, height: number, config?: GifEncoderConfig)
995
+
996
+ /** Width of the GIF canvas */
997
+ readonly width: number
998
+ /** Height of the GIF canvas */
999
+ readonly height: number
1000
+ /** Number of frames added so far */
1001
+ readonly frameCount: number
1002
+
1003
+ /**
1004
+ * Add a frame from RGBA pixel data
1005
+ * @param data - RGBA pixel data (must be width * height * 4 bytes)
1006
+ * @param width - Width of the frame in pixels
1007
+ * @param height - Height of the frame in pixels
1008
+ * @param config - Optional frame configuration
1009
+ */
1010
+ addFrame(data: Uint8Array, width: number, height: number, config?: GifFrameConfig): void
1011
+
1012
+ /**
1013
+ * Finish encoding and return the GIF data.
1014
+ * Clears all accumulated frames after encoding.
1015
+ * @throws Error if no frames have been added
1016
+ */
1017
+ finish(): Buffer
1018
+
1019
+ /**
1020
+ * Dispose of the encoder, clearing all accumulated frames without encoding.
1021
+ * Called automatically when using the `using` keyword.
1022
+ */
1023
+ dispose(): void
1024
+
1025
+ /**
1026
+ * Symbol.dispose implementation for ES2024 Explicit Resource Management.
1027
+ * Allows using `using encoder = new GifEncoder(...)` syntax.
1028
+ */
1029
+ [Symbol.dispose](): void
1030
+ }
1031
+ /**
1032
+ * https://en.wikipedia.org/wiki/Chroma_subsampling#Types_of_sampling_and_subsampling
1033
+ * https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_concepts
1034
+ */
1035
+ export enum ChromaSubsampling {
1036
+ /**
1037
+ * Each of the three Y'CbCr components has the same sample rate, thus there is no chroma subsampling. This scheme is sometimes used in high-end film scanners and cinematic post-production.
1038
+ * Note that "4:4:4" may instead be wrongly referring to R'G'B' color space, which implicitly also does not have any chroma subsampling (except in JPEG R'G'B' can be subsampled).
1039
+ * Formats such as HDCAM SR can record 4:4:4 R'G'B' over dual-link HD-SDI.
1040
+ */
1041
+ Yuv444 = 0,
1042
+ /**
1043
+ * The two chroma components are sampled at half the horizontal sample rate of luma: the horizontal chroma resolution is halved. This reduces the bandwidth of an uncompressed video signal by one-third.
1044
+ * Many high-end digital video formats and interfaces use this scheme:
1045
+ * - [AVC-Intra 100](https://en.wikipedia.org/wiki/AVC-Intra)
1046
+ * - [Digital Betacam](https://en.wikipedia.org/wiki/Betacam#Digital_Betacam)
1047
+ * - [Betacam SX](https://en.wikipedia.org/wiki/Betacam#Betacam_SX)
1048
+ * - [DVCPRO50](https://en.wikipedia.org/wiki/DV#DVCPRO) and [DVCPRO HD](https://en.wikipedia.org/wiki/DV#DVCPRO_HD)
1049
+ * - [Digital-S](https://en.wikipedia.org/wiki/Digital-S)
1050
+ * - [CCIR 601](https://en.wikipedia.org/wiki/Rec._601) / [Serial Digital Interface](https://en.wikipedia.org/wiki/Serial_digital_interface) / [D1](https://en.wikipedia.org/wiki/D-1_(Sony))
1051
+ * - [ProRes (HQ, 422, LT, and Proxy)](https://en.wikipedia.org/wiki/Apple_ProRes)
1052
+ * - [XDCAM HD422](https://en.wikipedia.org/wiki/XDCAM)
1053
+ * - [Canon MXF HD422](https://en.wikipedia.org/wiki/Canon_XF-300)
1054
+ */
1055
+ Yuv422 = 1,
1056
+ /**
1057
+ * n 4:2:0, the horizontal sampling is doubled compared to 4:1:1,
1058
+ * but as the **Cb** and **Cr** channels are only sampled on each alternate line in this scheme, the vertical resolution is halved.
1059
+ * The data rate is thus the same.
1060
+ * This fits reasonably well with the PAL color encoding system, since this has only half the vertical chrominance resolution of [NTSC](https://en.wikipedia.org/wiki/NTSC).
1061
+ * It would also fit extremely well with the [SECAM](https://en.wikipedia.org/wiki/SECAM) color encoding system,
1062
+ * since like that format, 4:2:0 only stores and transmits one color channel per line (the other channel being recovered from the previous line).
1063
+ * However, little equipment has actually been produced that outputs a SECAM analogue video signal.
1064
+ * In general, SECAM territories either have to use a PAL-capable display or a [transcoder](https://en.wikipedia.org/wiki/Transcoding) to convert the PAL signal to SECAM for display.
1065
+ */
1066
+ Yuv420 = 2,
1067
+ /**
1068
+ * What if the chroma subsampling model is 4:0:0?
1069
+ * That says to use every pixel of luma data, but that each row has 0 chroma samples applied to it. The resulting image, then, is comprised solely of the luminance data—a greyscale image.
1070
+ */
1071
+ Yuv400 = 3,
1072
+ }
1073
+
1074
+ /** OffscreenCanvas ImageEncodeOptions. */
1075
+ export interface ConvertToBlobOptions {
1076
+ /** Default 'image/png'; ASCII case-insensitive, and an unknown type is PNG. */
1077
+ type?: string
1078
+ /** 0 to 1 for JPEG, WebP (1 is lossless), AVIF and GIF. Default 1. */
1079
+ quality?: number
1080
+ }
1081
+
1082
+ export class Canvas {
1083
+ /**
1084
+ * A missing width or height is the default, 300 x 150, as is NaN, an infinity
1085
+ * or a non-zero number that converts to 0 (such as 0.5). 0 stays 0.
1086
+ */
1087
+ constructor(width?: number, height?: number, flag?: SvgExportFlag)
1088
+
1089
+ width: number
1090
+ height: number
1091
+ /**
1092
+ * Returns null for an id other than '2d', as browsers do for an unsupported id.
1093
+ * Declared before the '2d' overload, so `ReturnType` still gives the context.
1094
+ */
1095
+ getContext<T extends string>(
1096
+ contextType: T extends '2d' ? never : T,
1097
+ contextAttributes?: ContextAttributes,
1098
+ ): SKRSContext2D | null
1099
+ getContext(contextType: '2d', contextAttributes?: ContextAttributes): SKRSContext2D
1100
+ encodeSync(format: 'webp' | 'jpeg', quality?: number): Buffer
1101
+ encodeSync(format: 'jpeg', options: JpegEncodeOptions): Buffer
1102
+ encodeSync(format: 'png', options?: PngEncodeOptions): Buffer
1103
+ encodeSync(format: 'avif', cfg?: AvifConfig | number): Buffer
1104
+ encodeSync(format: 'gif', quality?: number): Buffer
1105
+ encode(format: 'webp' | 'jpeg', quality?: number): Promise<Buffer>
1106
+ encode(format: 'jpeg', options: JpegEncodeOptions): Promise<Buffer>
1107
+ encode(format: 'png', options?: PngEncodeOptions): Promise<Buffer>
1108
+ encode(format: 'avif', cfg?: AvifConfig | number): Promise<Buffer>
1109
+ encode(format: 'gif', quality?: number): Promise<Buffer>
1110
+ /** Writes no image metadata and uses default PNG options; use `encode` and stream the Buffer for those. */
1111
+ encodeStream(format: 'webp' | 'jpeg', quality?: number): ReadableStream<Buffer>
1112
+ encodeStream(format: 'png'): ReadableStream<Buffer>
1113
+ toBuffer(mime: 'image/png', options?: PngEncodeOptions): Buffer
1114
+ toBuffer(mime: 'image/jpeg' | 'image/webp', quality?: number): Buffer
1115
+ /**
1116
+ * JPEG with metadata, at quality 92: toBuffer does not read a quality from an
1117
+ * object. To set both, use `encodeSync('jpeg', { quality, ...metadata })`.
1118
+ */
1119
+ toBuffer(mime: 'image/jpeg', options: ImageMetadata): Buffer
1120
+ toBuffer(mime: 'image/avif', cfg?: AvifConfig | number): Buffer
1121
+ toBuffer(mime: 'image/gif', quality?: number): Buffer
1122
+ /** The stored pixels, premultiplied: RGBA bytes, or RGBA half floats (8 bytes a pixel) for colorType 'float16'. */
1123
+ data(): Buffer
1124
+ toDataURL(mime?: 'image/png'): string
1125
+ toDataURL(mime: 'image/jpeg' | 'image/webp', quality?: number): string
1126
+ toDataURL(mime: 'image/gif', quality?: number): string
1127
+ toDataURL(mime?: 'image/jpeg' | 'image/webp' | 'image/png' | 'image/gif', quality?: number): string
1128
+ toDataURL(mime?: 'image/avif', cfg?: AvifConfig | number): string
1129
+ /**
1130
+ * As in browsers: the type is ASCII case-insensitive and an unknown one is
1131
+ * PNG; the quality counts when it is a number from 0 to 1.
1132
+ */
1133
+ toDataURL(type?: string, quality?: any): string
1134
+
1135
+ toDataURLAsync(mime?: 'image/png'): Promise<string>
1136
+ toDataURLAsync(mime: 'image/jpeg' | 'image/webp', quality?: number): Promise<string>
1137
+ toDataURLAsync(mime: 'image/gif', quality?: number): Promise<string>
1138
+ toDataURLAsync(mime?: 'image/jpeg' | 'image/webp' | 'image/png' | 'image/gif', quality?: number): Promise<string>
1139
+ toDataURLAsync(mime?: 'image/avif', cfg?: AvifConfig | number): Promise<string>
1140
+ toDataURLAsync(type?: string, quality?: any): Promise<string>
1141
+
1142
+ toBlob(callback: (blob: Blob | null) => void, type?: string, quality?: any): void
1143
+ convertToBlob(options?: ConvertToBlobOptions): Promise<Blob>
1144
+ }
1145
+
1146
+ /**
1147
+ * A missing width or height is the default, 300 x 150, as is NaN, an infinity
1148
+ * or a non-zero number that converts to 0 (such as 0.5). 0 stays 0.
1149
+ */
1150
+ export function createCanvas(width?: number, height?: number): Canvas
1151
+
1152
+ export function createCanvas(width: number, height: number, svgExportFlag: SvgExportFlag): SvgCanvas
1153
+
1154
+ export declare class FontKey {
1155
+ // make it a unique type
1156
+ private readonly key: symbol
1157
+ readonly typefaceId: number
1158
+ }
1159
+
1160
+ export interface FontVariationAxis {
1161
+ /** OpenType tag as a 32-bit integer (e.g., 0x77676874 for 'wght') */
1162
+ tag: number
1163
+ /** Current value for this axis */
1164
+ value: number
1165
+ /** Minimum value for this axis */
1166
+ min: number
1167
+ /** Maximum value for this axis */
1168
+ max: number
1169
+ /** Default value for this axis */
1170
+ def: number
1171
+ /** Whether this axis should be hidden from UI */
1172
+ hidden: boolean
1173
+ }
1174
+
1175
+ /**
1176
+ * A font's `@font-face` descriptors, as `new FontFace(name, data, descriptors)`
1177
+ * takes them. An invalid value fails the registration (FontFace's status
1178
+ * 'error'); unknown keys are ignored. Values are kept in quarter steps, as
1179
+ * Chrome keeps them (300.7 is 300.5).
1180
+ */
1181
+ export interface FontFaceDescriptors {
1182
+ /**
1183
+ * A FontFace weight, as a CSS string or a number (converted with
1184
+ * `String()` first): `normal` (default), `bold`, `auto`, a number from 1
1185
+ * to 1000, a `calc()` number, or a range `<a> <b>` (a reversed one is
1186
+ * swapped). A `calc()` weight outside 1-1000 makes every descriptor
1187
+ * `auto`, as Chrome does. `bolder`, `lighter` and any other value are
1188
+ * invalid.
1189
+ */
1190
+ weight?: number | 'normal' | 'bold' | 'auto' | `${number}` | `${number} ${number}` | (string & {})
1191
+ /**
1192
+ * `normal` (default), `italic`, `oblique`, `oblique <angle>`,
1193
+ * `oblique <angle> <angle>` (a range; a reversed one is swapped) or
1194
+ * `auto`, in any ASCII case. An angle is a CSS angle such as `10deg`,
1195
+ * `0.2rad` or `calc(5deg)`; a written number from -90 to 90. A value that
1196
+ * is not a string is converted with `String()` first (`null` is 'null',
1197
+ * invalid).
1198
+ */
1199
+ style?: 'normal' | 'italic' | 'oblique' | 'auto' | `oblique ${string}`
1200
+ /**
1201
+ * `normal` (default), `auto`, one of the eight stretch keywords
1202
+ * (`ultra-condensed`, `extra-condensed`, `condensed`, `semi-condensed`,
1203
+ * `semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`), a
1204
+ * non-negative CSS percentage or `calc()` percentage, or a two-value
1205
+ * percentage range `<a> <b>` (a reversed one is swapped), in any ASCII
1206
+ * case. `normal` and `auto` keep the font's own `wdth` axis unclamped;
1207
+ * `100%` and the other keywords/percentages clamp it. A value that is not
1208
+ * a string is converted with `String()` first (`null` is 'null',
1209
+ * invalid).
1210
+ */
1211
+ stretch?: CanvasFontStretch | 'auto' | `${number}%` | `${number}% ${number}%` | (string & {})
1212
+ }
1213
+
1214
+ interface IGlobalFonts {
1215
+ readonly families: { family: string; styles: { weight: number; width: string; style: string }[] }[]
1216
+ /**
1217
+ * The FontKey, or null if it failed (also for invalid `descriptors`, which
1218
+ * registers nothing; a `descriptors` that is not an object, or a Symbol
1219
+ * value, throws a TypeError). `descriptors`: the font's descriptors under
1220
+ * this name; a text font list uses them where this name matches the font.
1221
+ * Without them (or with every one `auto`), `auto`: the face is picked as
1222
+ * `normal` (weight 400, upright, width 100%), and the font's own weight,
1223
+ * style and width axis ranges are kept for variations (no clamping).
1224
+ * Faces of one family are chosen by their descriptors, as with
1225
+ * `@font-face`. Without descriptors every face is `auto` and the newest
1226
+ * face wins; give `{ weight, style, stretch }` for each file of a family,
1227
+ * or use `loadFontsFromDir` (installed fonts match by the file's own style).
1228
+ * A font registered under a generic keyword (`serif`, `sans-serif`, ...):
1229
+ * for that keyword written unquoted, each face is matched by the file's
1230
+ * own style and descriptors are ignored (bold is made from weight 600, as
1231
+ * for other registered fonts). Only the quoted name (`"serif"`) follows
1232
+ * the descriptor and newest-face rule.
1233
+ */
1234
+ register(font: Buffer, nameAlias?: string, descriptors?: FontFaceDescriptors): FontKey | null
1235
+ /**
1236
+ * Absolute path. The FontKey, or null if it failed. `descriptors`: as
1237
+ * `register`'s; a file `loadFontsFromDir` loaded is an installed font and
1238
+ * takes none, so a call with them registers the file again. Faces of one
1239
+ * family are chosen as for `register`: without descriptors the newest
1240
+ * face wins. Exceptions: an unquoted generic keyword name, and a file
1241
+ * `loadFontsFromDir` already loaded, given again with no descriptors and
1242
+ * no other alias, which stays an installed font and keeps matching by the
1243
+ * file's own style.
1244
+ */
1245
+ registerFromPath(path: string, nameAlias?: string, descriptors?: FontFaceDescriptors): FontKey | null
1246
+ has(name: string): boolean
1247
+ loadFontsFromDir(path: string): number
1248
+ /**
1249
+ * Set an alias for a font family.
1250
+ * @param fontName The original font family name
1251
+ * @param alias The alias name to set
1252
+ * @returns true if the alias was set successfully, false if the font family doesn't exist
1253
+ */
1254
+ setAlias(fontName: string, alias: string): boolean
1255
+ remove(key: FontKey): boolean
1256
+ /**
1257
+ * Remove multiple fonts by their keys in a single operation.
1258
+ * More efficient than calling remove() multiple times as it triggers only one rebuild.
1259
+ * @param fontKeys Array of FontKey objects to remove
1260
+ * @returns Number of fonts successfully removed
1261
+ */
1262
+ removeBatch(fontKeys: FontKey[]): number
1263
+ /**
1264
+ * Remove ALL registered fonts.
1265
+ * @returns Number of fonts removed
1266
+ */
1267
+ removeAll(): number
1268
+ /**
1269
+ * Get variation axes for a specific font instance
1270
+ * @param familyName The font family name
1271
+ * @param weight Font weight (100-900)
1272
+ * @param width Font width/stretch value
1273
+ * @param slant Font slant (0 = upright, 1 = italic, 2 = oblique)
1274
+ * @returns Array of variation axes or empty array if not a variable font
1275
+ */
1276
+ getVariationAxes(familyName: string, weight: number, width: number, slant: number): FontVariationAxis[]
1277
+ /**
1278
+ * Check if a font has variable font capabilities
1279
+ * @param familyName The font family name
1280
+ * @param weight Font weight (100-900)
1281
+ * @param width Font width/stretch value
1282
+ * @param slant Font slant (0 = upright, 1 = italic, 2 = oblique)
1283
+ * @returns true if the font is a variable font
1284
+ */
1285
+ hasVariations(familyName: string, weight: number, width: number, slant: number): boolean
1286
+ }
1287
+
1288
+ export const GlobalFonts: IGlobalFonts
1289
+
1290
+ export enum PathOp {
1291
+ Difference = 0, // subtract the op path from the first path
1292
+ Intersect = 1, // intersect the two paths
1293
+ Union = 2, // union (inclusive-or) the two paths
1294
+ Xor = 3, // exclusive-or the two paths
1295
+ ReverseDifference = 4, // subtract the first path from the op path
1296
+ }
1297
+
1298
+ export enum FillType {
1299
+ Winding = 0,
1300
+ EvenOdd = 1,
1301
+ InverseWinding = 2,
1302
+ InverseEvenOdd = 3,
1303
+ }
1304
+
1305
+ export enum StrokeJoin {
1306
+ Miter = 0,
1307
+ Round = 1,
1308
+ Bevel = 2,
1309
+ }
1310
+
1311
+ export enum StrokeCap {
1312
+ Butt = 0,
1313
+ Round = 1,
1314
+ Square = 2,
1315
+ }
1316
+
1317
+ export enum SvgExportFlag {
1318
+ ConvertTextToPaths = 0x01,
1319
+ NoPrettyXML = 0x02,
1320
+ RelativePathEncoding = 0x04,
1321
+ }
1322
+
1323
+ export function convertSVGTextToPath(svg: Buffer | string): Buffer
1324
+
1325
+ export interface LoadImageOptions {
1326
+ alt?: string
1327
+ maxRedirects?: number
1328
+ requestOptions?: import('http').RequestOptions
1329
+ }
1330
+
1331
+ export function loadImage(
1332
+ source: string | URL | Buffer | ArrayBufferLike | Uint8Array | Image | import('stream').Readable,
1333
+ options?: LoadImageOptions,
1334
+ ): Promise<Image>
1335
+
1336
+ export interface PDFMetadata {
1337
+ /// The document's title
1338
+ title?: string
1339
+ /// The name of the person who created the document
1340
+ author?: string
1341
+ /// The subject of the document
1342
+ subject?: string
1343
+ /// Keywords associated with the document
1344
+ keywords?: string
1345
+ /// The product that created the original document
1346
+ creator?: string
1347
+ /// The product that is converting this document to PDF (defaults to "Skia/PDF")
1348
+ producer?: string
1349
+ /// The DPI for rasterization (default: 72.0)
1350
+ rasterDPI?: number
1351
+ /// Encoding quality: 0-100 for lossy JPEG, 101 for lossless (default: 101)
1352
+ encodingQuality?: number
1353
+ /// Whether to conform to PDF/A-2b standard (default: false)
1354
+ pdfa?: boolean
1355
+ /// Compression level: -1 (default), 0 (none), 1 (low/fast), 6 (average), 9 (high/slow)
1356
+ compressionLevel?: number
1357
+ }
1358
+
1359
+ export interface Rect {
1360
+ left: number
1361
+ top: number
1362
+ right: number
1363
+ bottom: number
1364
+ }
1365
+
1366
+ export declare class PDFDocument {
1367
+ constructor(metadata?: PDFMetadata | undefined | null)
1368
+ beginPage(width: number, height: number, rect?: Rect | undefined | null): CanvasRenderingContext2D
1369
+ endPage(): void
1370
+ close(): Buffer
1371
+ }
1372
+
1373
+ export interface LottieAnimationOptions {
1374
+ /** Base path for resolving external resources (images, fonts) */
1375
+ resourcePath?: string
1376
+ }
1377
+
1378
+ export interface LottieRenderRect {
1379
+ x: number
1380
+ y: number
1381
+ width: number
1382
+ height: number
1383
+ }
1384
+
1385
+ /**
1386
+ * Lottie animation class for loading and rendering Lottie JSON files.
1387
+ *
1388
+ * @example
1389
+ * ```typescript
1390
+ * import { LottieAnimation, createCanvas } from '@napi-rs/canvas'
1391
+ *
1392
+ * const animation = LottieAnimation.loadFromFile('./animation.json')
1393
+ * const canvas = createCanvas(animation.width, animation.height)
1394
+ * const ctx = canvas.getContext('2d')
1395
+ *
1396
+ * // Render frame 0
1397
+ * animation.seekFrame(0)
1398
+ * animation.render(ctx)
1399
+ *
1400
+ * // Save to PNG
1401
+ * const buffer = canvas.toBuffer('image/png')
1402
+ * ```
1403
+ */
1404
+ export declare class LottieAnimation {
1405
+ /**
1406
+ * Load animation from JSON string or Buffer
1407
+ * @param data - JSON string or Buffer containing Lottie animation data
1408
+ * @param options - Optional configuration
1409
+ */
1410
+ static loadFromData(data: string | Buffer, options?: LottieAnimationOptions): LottieAnimation
1411
+
1412
+ /**
1413
+ * Load animation from file path
1414
+ * External assets are resolved relative to the file's directory
1415
+ * @param path - Path to the Lottie JSON file
1416
+ */
1417
+ static loadFromFile(path: string): LottieAnimation
1418
+
1419
+ /** Animation duration in seconds */
1420
+ readonly duration: number
1421
+
1422
+ /** Frame rate (frames per second) */
1423
+ readonly fps: number
1424
+
1425
+ /** Total frame count */
1426
+ readonly frames: number
1427
+
1428
+ /** Animation width in pixels */
1429
+ readonly width: number
1430
+
1431
+ /** Animation height in pixels */
1432
+ readonly height: number
1433
+
1434
+ /** Lottie format version string */
1435
+ readonly version: string
1436
+
1437
+ /** Animation in-point (start frame) */
1438
+ readonly inPoint: number
1439
+
1440
+ /** Animation out-point (end frame) */
1441
+ readonly outPoint: number
1442
+
1443
+ /**
1444
+ * Seek to normalized position
1445
+ * @param t - Position between 0.0 (start) and 1.0 (end)
1446
+ */
1447
+ seek(t: number): void
1448
+
1449
+ /**
1450
+ * Seek to specific frame index
1451
+ * @param frame - Frame index (0 = first frame)
1452
+ */
1453
+ seekFrame(frame: number): void
1454
+
1455
+ /**
1456
+ * Seek to specific time in seconds
1457
+ * @param seconds - Time in seconds from start
1458
+ */
1459
+ seekTime(seconds: number): void
1460
+
1461
+ /**
1462
+ * Render current frame to canvas context
1463
+ * @param ctx - Canvas 2D rendering context
1464
+ * @param dst - Optional destination rectangle for scaling/positioning
1465
+ */
1466
+ render(ctx: CanvasRenderingContext2D, dst?: LottieRenderRect): void
1467
+ }