index.d.ts 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. import { ReadableStream } from 'node:stream/web'
  2. // Clear all type of caches in Skia
  3. export function clearAllCache(): void
  4. interface CanvasRenderingContext2D
  5. extends CanvasCompositing,
  6. CanvasDrawPath,
  7. CanvasFillStrokeStyles,
  8. CanvasFilters,
  9. CanvasImageData,
  10. CanvasImageSmoothing,
  11. CanvasPath,
  12. CanvasPathDrawingStyles,
  13. CanvasRect,
  14. CanvasSettings,
  15. CanvasShadowStyles,
  16. CanvasState,
  17. CanvasText,
  18. CanvasTextDrawingStyles,
  19. CanvasTransform,
  20. CanvasPDFAnnotations { }
  21. interface CanvasState {
  22. isContextLost(): boolean
  23. reset(): void
  24. restore(): void
  25. save(): void
  26. }
  27. interface CanvasShadowStyles {
  28. shadowBlur: number
  29. shadowColor: string
  30. shadowOffsetX: number
  31. shadowOffsetY: number
  32. }
  33. interface CanvasRenderingContext2DSettings {
  34. alpha?: boolean
  35. colorSpace?: PredefinedColorSpace
  36. desynchronized?: boolean
  37. willReadFrequently?: boolean
  38. }
  39. interface CanvasSettings {
  40. getContextAttributes(): CanvasRenderingContext2DSettings
  41. }
  42. interface CanvasRect {
  43. clearRect(x: number, y: number, w: number, h: number): void
  44. fillRect(x: number, y: number, w: number, h: number): void
  45. strokeRect(x: number, y: number, w: number, h: number): void
  46. }
  47. interface TextMetrics {
  48. readonly actualBoundingBoxAscent: number
  49. readonly actualBoundingBoxDescent: number
  50. readonly actualBoundingBoxLeft: number
  51. readonly actualBoundingBoxRight: number
  52. readonly alphabeticBaseline: number
  53. readonly emHeightAscent: number
  54. readonly emHeightDescent: number
  55. readonly fontBoundingBoxAscent: number
  56. readonly fontBoundingBoxDescent: number
  57. readonly hangingBaseline: number
  58. readonly ideographicBaseline: number
  59. readonly width: number
  60. }
  61. interface CanvasText {
  62. fillText(text: string, x: number, y: number, maxWidth?: number): void
  63. measureText(text: string): TextMetrics
  64. strokeText(text: string, x: number, y: number, maxWidth?: number): void
  65. }
  66. type CanvasLineCap = 'butt' | 'round' | 'square'
  67. type CanvasLineJoin = 'bevel' | 'miter' | 'round'
  68. interface CanvasPathDrawingStyles {
  69. lineCap: CanvasLineCap
  70. lineDashOffset: number
  71. lineJoin: CanvasLineJoin
  72. lineWidth: number
  73. miterLimit: number
  74. getLineDash(): number[]
  75. setLineDash(segments: number[]): void
  76. }
  77. interface CanvasPath {
  78. arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
  79. arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
  80. bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void
  81. closePath(): void
  82. ellipse(
  83. x: number,
  84. y: number,
  85. radiusX: number,
  86. radiusY: number,
  87. rotation: number,
  88. startAngle: number,
  89. endAngle: number,
  90. counterclockwise?: boolean,
  91. ): void
  92. lineTo(x: number, y: number): void
  93. moveTo(x: number, y: number): void
  94. quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
  95. rect(x: number, y: number, w: number, h: number): void
  96. roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | (number | DOMPointInit)[]): void
  97. }
  98. type ImageSmoothingQuality = 'high' | 'low' | 'medium'
  99. interface CanvasImageSmoothing {
  100. imageSmoothingEnabled: boolean
  101. imageSmoothingQuality: ImageSmoothingQuality
  102. }
  103. interface CanvasTransform {
  104. resetTransform(): void
  105. rotate(angle: number): void
  106. scale(x: number, y: number): void
  107. setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void
  108. setTransform(transform?: DOMMatrix2DInit): void
  109. transform(a: number, b: number, c: number, d: number, e: number, f: number): void
  110. translate(x: number, y: number): void
  111. }
  112. interface CanvasPDFAnnotations {
  113. /**
  114. * Create a clickable URL link annotation in a PDF document.
  115. * This is only effective when used with PDF documents.
  116. * @param left - Left coordinate of the link rectangle
  117. * @param top - Top coordinate of the link rectangle
  118. * @param right - Right coordinate of the link rectangle
  119. * @param bottom - Bottom coordinate of the link rectangle
  120. * @param url - The URL to link to
  121. */
  122. annotateLinkUrl(left: number, top: number, right: number, bottom: number, url: string): void
  123. /**
  124. * Create a named destination at a specific point in a PDF document.
  125. * This destination can be used as a target for internal links.
  126. * @param x - X coordinate of the destination point
  127. * @param y - Y coordinate of the destination point
  128. * @param name - Name identifier for the destination
  129. */
  130. annotateNamedDestination(x: number, y: number, name: string): void
  131. /**
  132. * Create a link to a named destination within the PDF document.
  133. * This is only effective when used with PDF documents.
  134. * @param left - Left coordinate of the link rectangle
  135. * @param top - Top coordinate of the link rectangle
  136. * @param right - Right coordinate of the link rectangle
  137. * @param bottom - Bottom coordinate of the link rectangle
  138. * @param name - Name of the destination to link to
  139. */
  140. annotateLinkToDestination(left: number, top: number, right: number, bottom: number, name: string): void
  141. }
  142. type PredefinedColorSpace = 'display-p3' | 'srgb'
  143. interface ImageDataSettings {
  144. colorSpace?: PredefinedColorSpace
  145. }
  146. interface CanvasImageData {
  147. createImageData(sw: number, sh: number, settings?: ImageDataSettings): ImageData
  148. createImageData(imagedata: ImageData): ImageData
  149. getImageData(sx: number, sy: number, sw: number, sh: number, settings?: ImageDataSettings): ImageData
  150. putImageData(imagedata: ImageData, dx: number, dy: number): void
  151. putImageData(
  152. imagedata: ImageData,
  153. dx: number,
  154. dy: number,
  155. dirtyX: number,
  156. dirtyY: number,
  157. dirtyWidth: number,
  158. dirtyHeight: number,
  159. ): void
  160. }
  161. type CanvasDirection = 'inherit' | 'ltr' | 'rtl'
  162. type CanvasFontKerning = 'auto' | 'none' | 'normal'
  163. type CanvasFontStretch =
  164. | 'condensed'
  165. | 'expanded'
  166. | 'extra-condensed'
  167. | 'extra-expanded'
  168. | 'normal'
  169. | 'semi-condensed'
  170. | 'semi-expanded'
  171. | 'ultra-condensed'
  172. | 'ultra-expanded'
  173. type CanvasFontVariantCaps =
  174. | 'all-petite-caps'
  175. | 'all-small-caps'
  176. | 'normal'
  177. | 'petite-caps'
  178. | 'small-caps'
  179. | 'titling-caps'
  180. | 'unicase'
  181. type CanvasTextAlign = 'center' | 'end' | 'left' | 'right' | 'start'
  182. type CanvasTextBaseline = 'alphabetic' | 'bottom' | 'hanging' | 'ideographic' | 'middle' | 'top'
  183. type CanvasTextRendering = 'auto' | 'geometricPrecision' | 'optimizeLegibility' | 'optimizeSpeed'
  184. interface CanvasTextDrawingStyles {
  185. direction: CanvasDirection
  186. font: string
  187. fontKerning: CanvasFontKerning
  188. fontStretch: CanvasFontStretch
  189. fontVariantCaps: CanvasFontVariantCaps
  190. letterSpacing: string
  191. textAlign: CanvasTextAlign
  192. textBaseline: CanvasTextBaseline
  193. textRendering: CanvasTextRendering
  194. wordSpacing: string
  195. fontVariationSettings: string
  196. lang: string
  197. }
  198. interface CanvasFilters {
  199. filter: string
  200. }
  201. interface CanvasFillStrokeStyles {
  202. fillStyle: string | CanvasGradient | CanvasPattern
  203. strokeStyle: string | CanvasGradient | CanvasPattern
  204. createConicGradient(startAngle: number, x: number, y: number): CanvasGradient
  205. createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient
  206. createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient
  207. }
  208. type CanvasFillRule = 'evenodd' | 'nonzero'
  209. interface CanvasDrawPath {
  210. beginPath(): void
  211. clip(fillRule?: CanvasFillRule): void
  212. clip(path: Path2D, fillRule?: CanvasFillRule): void
  213. fill(fillRule?: CanvasFillRule): void
  214. fill(path: Path2D, fillRule?: CanvasFillRule): void
  215. isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean
  216. isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean
  217. isPointInStroke(x: number, y: number): boolean
  218. isPointInStroke(path: Path2D, x: number, y: number): boolean
  219. stroke(): void
  220. stroke(path: Path2D): void
  221. }
  222. type GlobalCompositeOperation =
  223. | 'color'
  224. | 'color-burn'
  225. | 'color-dodge'
  226. | 'copy'
  227. | 'darken'
  228. | 'destination-atop'
  229. | 'destination-in'
  230. | 'destination-out'
  231. | 'destination-over'
  232. | 'difference'
  233. | 'exclusion'
  234. | 'hard-light'
  235. | 'hue'
  236. | 'lighten'
  237. | 'lighter'
  238. | 'luminosity'
  239. | 'multiply'
  240. | 'overlay'
  241. | 'saturation'
  242. | 'screen'
  243. | 'soft-light'
  244. | 'source-atop'
  245. | 'source-in'
  246. | 'source-out'
  247. | 'source-over'
  248. | 'xor'
  249. interface CanvasCompositing {
  250. globalAlpha: number
  251. globalCompositeOperation: GlobalCompositeOperation
  252. }
  253. interface DOMPointInit {
  254. w?: number
  255. x?: number
  256. y?: number
  257. z?: number
  258. }
  259. interface CanvasPattern {
  260. setTransform(transform?: DOMMatrix2DInit): void
  261. }
  262. interface CanvasGradient {
  263. addColorStop(offset: number, color: string): void
  264. }
  265. interface DOMRectInit {
  266. height?: number
  267. width?: number
  268. x?: number
  269. y?: number
  270. }
  271. interface DOMMatrixInit extends DOMMatrix2DInit {
  272. is2D?: boolean
  273. m13?: number
  274. m14?: number
  275. m23?: number
  276. m24?: number
  277. m31?: number
  278. m32?: number
  279. m33?: number
  280. m34?: number
  281. m43?: number
  282. m44?: number
  283. }
  284. // ----------- added types
  285. export interface DOMMatrix2DInit {
  286. a: number
  287. b: number
  288. c: number
  289. d: number
  290. e: number
  291. f: number
  292. }
  293. interface DOMMatrixReadOnly {
  294. readonly a: number
  295. readonly b: number
  296. readonly c: number
  297. readonly d: number
  298. readonly e: number
  299. readonly f: number
  300. readonly is2D: boolean
  301. readonly isIdentity: boolean
  302. readonly m11: number
  303. readonly m12: number
  304. readonly m13: number
  305. readonly m14: number
  306. readonly m21: number
  307. readonly m22: number
  308. readonly m23: number
  309. readonly m24: number
  310. readonly m31: number
  311. readonly m32: number
  312. readonly m33: number
  313. readonly m34: number
  314. readonly m41: number
  315. readonly m42: number
  316. readonly m43: number
  317. readonly m44: number
  318. flipX(): DOMMatrix
  319. flipY(): DOMMatrix
  320. inverse(): DOMMatrix
  321. multiply(other?: DOMMatrixInit): DOMMatrix
  322. rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix
  323. rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix
  324. rotateFromVector(x?: number, y?: number): DOMMatrix
  325. scale(
  326. scaleX?: number,
  327. scaleY?: number,
  328. scaleZ?: number,
  329. originX?: number,
  330. originY?: number,
  331. originZ?: number,
  332. ): DOMMatrix
  333. scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix
  334. skewX(sx?: number): DOMMatrix
  335. skewY(sy?: number): DOMMatrix
  336. toFloat32Array(): Float32Array
  337. toFloat64Array(): Float64Array
  338. transformPoint(point?: DOMPointInit): DOMPoint
  339. translate(tx?: number, ty?: number, tz?: number): DOMMatrix
  340. toString(): string
  341. }
  342. export interface DOMMatrix extends DOMMatrixReadOnly {
  343. a: number
  344. b: number
  345. c: number
  346. d: number
  347. e: number
  348. f: number
  349. m11: number
  350. m12: number
  351. m13: number
  352. m14: number
  353. m21: number
  354. m22: number
  355. m23: number
  356. m24: number
  357. m31: number
  358. m32: number
  359. m33: number
  360. m34: number
  361. m41: number
  362. m42: number
  363. m43: number
  364. m44: number
  365. invertSelf(): DOMMatrix
  366. multiplySelf(other?: DOMMatrixInit): DOMMatrix
  367. preMultiplySelf(other?: DOMMatrixInit): DOMMatrix
  368. rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix
  369. rotateFromVectorSelf(x?: number, y?: number): DOMMatrix
  370. rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix
  371. scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix
  372. scaleSelf(
  373. scaleX?: number,
  374. scaleY?: number,
  375. scaleZ?: number,
  376. originX?: number,
  377. originY?: number,
  378. originZ?: number,
  379. ): DOMMatrix
  380. setMatrixValue(transformList: string): DOMMatrix
  381. skewXSelf(sx?: number): DOMMatrix
  382. skewYSelf(sy?: number): DOMMatrix
  383. translateSelf(tx?: number, ty?: number, tz?: number): DOMMatrix
  384. toJSON(): { [K in OmitNeverOfMatrix]: DOMMatrix[K] }
  385. }
  386. type OmitMatrixMethod = { [K in keyof DOMMatrix]: DOMMatrix[K] extends (...args: any[]) => any ? never : K }
  387. type OmitNeverOfMatrix = OmitMatrixMethod[keyof OmitMatrixMethod]
  388. export const DOMMatrix: {
  389. prototype: DOMMatrix
  390. new(init?: string | number[]): DOMMatrix
  391. fromFloat32Array(array32: Float32Array): DOMMatrix
  392. fromFloat64Array(array64: Float64Array): DOMMatrix
  393. fromMatrix(other?: DOMMatrixInit): DOMMatrix
  394. }
  395. interface DOMRectReadOnly {
  396. readonly bottom: number
  397. readonly height: number
  398. readonly left: number
  399. readonly right: number
  400. readonly top: number
  401. readonly width: number
  402. readonly x: number
  403. readonly y: number
  404. }
  405. export interface DOMRect extends DOMRectReadOnly {
  406. height: number
  407. width: number
  408. x: number
  409. y: number
  410. toJSON(): Omit<this, 'toJSON' | 'fromRect'>
  411. }
  412. export const DOMRect: {
  413. prototype: DOMRect
  414. new(x?: number, y?: number, width?: number, height?: number): DOMRect
  415. fromRect(other?: DOMRectInit): DOMRect
  416. }
  417. interface DOMPointReadOnly {
  418. readonly w: number
  419. readonly x: number
  420. readonly y: number
  421. readonly z: number
  422. matrixTransform(matrix?: DOMMatrixInit): DOMPoint
  423. }
  424. export interface DOMPoint extends DOMPointReadOnly {
  425. w: number
  426. x: number
  427. y: number
  428. z: number
  429. toJSON(): Omit<DOMPoint, 'matrixTransform' | 'toJSON'>
  430. }
  431. export const DOMPoint: {
  432. prototype: DOMPoint
  433. new(x?: number, y?: number, z?: number, w?: number): DOMPoint
  434. fromPoint(other?: DOMPointInit): DOMPoint
  435. }
  436. export class ImageData {
  437. /**
  438. * Returns the one-dimensional array containing the data in RGBA order, as integers in the range 0 to 255.
  439. */
  440. readonly data: Uint8ClampedArray
  441. /**
  442. * Returns the actual dimensions of the data in the ImageData object, in pixels.
  443. */
  444. readonly height: number
  445. /**
  446. * Returns the actual dimensions of the data in the ImageData object, in pixels.
  447. */
  448. readonly width: number
  449. constructor(sw: number, sh: number, attr?: { colorSpace?: ColorSpace })
  450. constructor(imageData: ImageData, attr?: { colorSpace?: ColorSpace })
  451. constructor(data: Uint8ClampedArray | Uint16Array | Float16Array | Float32Array, sw: number, sh?: number)
  452. }
  453. export class Image {
  454. constructor()
  455. // attrs only affects SVG
  456. constructor(width: number, height: number, attrs?: { colorSpace?: ColorSpace })
  457. width: number
  458. height: number
  459. readonly naturalWidth: number
  460. readonly naturalHeight: number
  461. readonly complete: boolean
  462. readonly currentSrc: string | null
  463. alt: string
  464. // the src can be a Uint8Array or a string
  465. // if it's a string, it can be a file path, a data URL, a remote URL, or a SVG string
  466. src: Uint8Array | string
  467. onload?(): void
  468. onerror?(err: Error): void
  469. decode(): Promise<void>
  470. }
  471. export class Path2D {
  472. constructor(path?: Path2D | string)
  473. addPath(path: Path2D, transform?: DOMMatrix2DInit): void
  474. arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void
  475. arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
  476. bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void
  477. closePath(): void
  478. ellipse(
  479. x: number,
  480. y: number,
  481. radiusX: number,
  482. radiusY: number,
  483. rotation: number,
  484. startAngle: number,
  485. endAngle: number,
  486. anticlockwise?: boolean,
  487. ): void
  488. lineTo(x: number, y: number): void
  489. moveTo(x: number, y: number): void
  490. quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
  491. rect(x: number, y: number, w: number, h: number): void
  492. roundRect(x: number, y: number, w: number, h: number, radii?: number | number[]): void
  493. // PathKit methods
  494. op(path: Path2D, operation: PathOp): Path2D
  495. toSVGString(): string
  496. getFillType(): FillType
  497. getFillTypeString(): string
  498. setFillType(type: FillType): void
  499. simplify(): Path2D
  500. asWinding(): Path2D
  501. stroke(stroke?: StrokeOptions): Path2D
  502. transform(transform: DOMMatrix2DInit): Path2D
  503. getBounds(): [left: number, top: number, right: number, bottom: number]
  504. computeTightBounds(): [left: number, top: number, right: number, bottom: number]
  505. trim(start: number, end: number, isComplement?: boolean): Path2D
  506. dash(on: number, off: number, phase: number): Path2D
  507. round(radius: number): Path2D
  508. equals(path: Path2D): boolean
  509. }
  510. export interface StrokeOptions {
  511. width?: number
  512. miterLimit?: number
  513. cap?: StrokeCap
  514. join?: StrokeJoin
  515. }
  516. export interface SKRSContext2D extends CanvasRenderingContext2D {
  517. canvas: Canvas
  518. /**
  519. * @param startAngle The angle at which to begin the gradient, in radians. Angle measurements start vertically above the centre and move around clockwise.
  520. * @param x The x-axis coordinate of the centre of the gradient.
  521. * @param y The y-axis coordinate of the centre of the gradient.
  522. */
  523. createConicGradient(startAngle: number, x: number, y: number): CanvasGradient
  524. drawImage(image: Image | Canvas, dx: number, dy: number): void
  525. drawImage(image: Image | Canvas, dx: number, dy: number, dw: number, dh: number): void
  526. drawImage(
  527. image: Image | Canvas,
  528. sx: number,
  529. sy: number,
  530. sw: number,
  531. sh: number,
  532. dx: number,
  533. dy: number,
  534. dw: number,
  535. dh: number,
  536. ): void
  537. /**
  538. * Draw another canvas, preserving vector graphics when possible.
  539. * When the source canvas has recorded operations, this method preserves the
  540. * SkPicture representation without rasterization, which can be faster than
  541. * drawImage. Falls back to bitmap rendering if no picture is available.
  542. */
  543. drawCanvas(canvas: Canvas, dx: number, dy: number): void
  544. drawCanvas(canvas: Canvas, dx: number, dy: number, dWidth: number, dHeight: number): void
  545. drawCanvas(
  546. canvas: Canvas,
  547. sx: number,
  548. sy: number,
  549. sWidth: number,
  550. sHeight: number,
  551. dx: number,
  552. dy: number,
  553. dWidth: number,
  554. dHeight: number,
  555. ): void
  556. createPattern(
  557. image: Image | ImageData | Canvas | SvgCanvas,
  558. repeat: 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat' | null,
  559. ): CanvasPattern
  560. getContextAttributes(): { alpha: boolean; desynchronized: boolean }
  561. getTransform(): DOMMatrix
  562. letterSpacing: string
  563. wordSpacing: string
  564. }
  565. export type ColorSpace = 'srgb' | 'display-p3'
  566. export interface ContextAttributes {
  567. alpha?: boolean
  568. colorSpace?: ColorSpace
  569. }
  570. export interface SvgCanvas {
  571. width: number
  572. height: number
  573. getContext(contextType: '2d', contextAttributes?: ContextAttributes): SKRSContext2D
  574. getContent(): Buffer
  575. }
  576. export interface AvifConfig {
  577. /** 0-100 scale, 100 is lossless */
  578. quality?: number
  579. /** 0-100 scale */
  580. alphaQuality?: number
  581. /** rav1e preset 1 (slow) 10 (fast but crappy), default is 4 */
  582. speed?: number
  583. /** How many threads should be used (0 = match core count) */
  584. threads?: number
  585. /** set to '4:2:0' to use chroma subsampling, default '4:4:4' */
  586. chromaSubsampling?: ChromaSubsampling
  587. }
  588. /** GIF encoding configuration for single-frame encoding */
  589. export interface GifConfig {
  590. /**
  591. * Quality for NeuQuant color quantization (1-30, lower = slower but better quality)
  592. * @default 10
  593. */
  594. quality?: number
  595. }
  596. /** Configuration for the GIF encoder (animated GIFs) */
  597. export interface GifEncoderConfig {
  598. /**
  599. * Loop count: 0 = infinite loop, positive number = finite loops
  600. * @default 0 (infinite)
  601. */
  602. repeat?: number
  603. /**
  604. * Quality for NeuQuant color quantization (1-30, lower = slower but better quality)
  605. * @default 10
  606. */
  607. quality?: number
  608. }
  609. /** Configuration for individual GIF frames */
  610. export interface GifFrameConfig {
  611. /**
  612. * Frame delay in milliseconds
  613. * @default 100
  614. */
  615. delay?: number
  616. /** Disposal method for this frame */
  617. disposal?: GifDisposal
  618. /** Transparent color index (0-255), if the frame has transparency */
  619. transparent?: number
  620. /** X offset of this frame within the canvas */
  621. left?: number
  622. /** Y offset of this frame within the canvas */
  623. top?: number
  624. }
  625. /** GIF frame disposal method */
  626. export enum GifDisposal {
  627. /** Keep the frame visible (default) */
  628. Keep = 0,
  629. /** Clear the frame area to the background color */
  630. Background = 1,
  631. /** Restore to the previous frame */
  632. Previous = 2,
  633. }
  634. /**
  635. * GIF Encoder for creating animated GIFs.
  636. * Implements `Disposable` interface for use with the `using` keyword (ES2024).
  637. *
  638. * @example
  639. * ```typescript
  640. * // Basic usage
  641. * const encoder = new GifEncoder(100, 100, { repeat: 0, quality: 10 });
  642. * encoder.addFrame(rgbaData, 100, 100, { delay: 100 });
  643. * encoder.addFrame(rgbaData2, 100, 100, { delay: 100 });
  644. * const buffer = encoder.finish();
  645. *
  646. * // With `using` keyword (automatic cleanup)
  647. * {
  648. * using encoder = new GifEncoder(100, 100);
  649. * encoder.addFrame(frame1, 100, 100, { delay: 100 });
  650. * const buffer = encoder.finish();
  651. * } // encoder automatically disposed
  652. * ```
  653. */
  654. export class GifEncoder implements Disposable {
  655. /**
  656. * Create a new GIF encoder with the specified dimensions
  657. * @param width - Width of the GIF canvas in pixels
  658. * @param height - Height of the GIF canvas in pixels
  659. * @param config - Optional encoder configuration
  660. */
  661. constructor(width: number, height: number, config?: GifEncoderConfig)
  662. /** Width of the GIF canvas */
  663. readonly width: number
  664. /** Height of the GIF canvas */
  665. readonly height: number
  666. /** Number of frames added so far */
  667. readonly frameCount: number
  668. /**
  669. * Add a frame from RGBA pixel data
  670. * @param data - RGBA pixel data (must be width * height * 4 bytes)
  671. * @param width - Width of the frame in pixels
  672. * @param height - Height of the frame in pixels
  673. * @param config - Optional frame configuration
  674. */
  675. addFrame(data: Uint8Array, width: number, height: number, config?: GifFrameConfig): void
  676. /**
  677. * Finish encoding and return the GIF data.
  678. * Clears all accumulated frames after encoding.
  679. * @throws Error if no frames have been added
  680. */
  681. finish(): Buffer
  682. /**
  683. * Dispose of the encoder, clearing all accumulated frames without encoding.
  684. * Called automatically when using the `using` keyword.
  685. */
  686. dispose(): void
  687. /**
  688. * Symbol.dispose implementation for ES2024 Explicit Resource Management.
  689. * Allows using `using encoder = new GifEncoder(...)` syntax.
  690. */
  691. [Symbol.dispose](): void
  692. }
  693. /**
  694. * https://en.wikipedia.org/wiki/Chroma_subsampling#Types_of_sampling_and_subsampling
  695. * https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Video_concepts
  696. */
  697. export enum ChromaSubsampling {
  698. /**
  699. * 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.
  700. * 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).
  701. * Formats such as HDCAM SR can record 4:4:4 R'G'B' over dual-link HD-SDI.
  702. */
  703. Yuv444 = 0,
  704. /**
  705. * 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.
  706. * Many high-end digital video formats and interfaces use this scheme:
  707. * - [AVC-Intra 100](https://en.wikipedia.org/wiki/AVC-Intra)
  708. * - [Digital Betacam](https://en.wikipedia.org/wiki/Betacam#Digital_Betacam)
  709. * - [Betacam SX](https://en.wikipedia.org/wiki/Betacam#Betacam_SX)
  710. * - [DVCPRO50](https://en.wikipedia.org/wiki/DV#DVCPRO) and [DVCPRO HD](https://en.wikipedia.org/wiki/DV#DVCPRO_HD)
  711. * - [Digital-S](https://en.wikipedia.org/wiki/Digital-S)
  712. * - [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))
  713. * - [ProRes (HQ, 422, LT, and Proxy)](https://en.wikipedia.org/wiki/Apple_ProRes)
  714. * - [XDCAM HD422](https://en.wikipedia.org/wiki/XDCAM)
  715. * - [Canon MXF HD422](https://en.wikipedia.org/wiki/Canon_XF-300)
  716. */
  717. Yuv422 = 1,
  718. /**
  719. * n 4:2:0, the horizontal sampling is doubled compared to 4:1:1,
  720. * but as the **Cb** and **Cr** channels are only sampled on each alternate line in this scheme, the vertical resolution is halved.
  721. * The data rate is thus the same.
  722. * 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).
  723. * It would also fit extremely well with the [SECAM](https://en.wikipedia.org/wiki/SECAM) color encoding system,
  724. * 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).
  725. * However, little equipment has actually been produced that outputs a SECAM analogue video signal.
  726. * 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.
  727. */
  728. Yuv420 = 2,
  729. /**
  730. * What if the chroma subsampling model is 4:0:0?
  731. * 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.
  732. */
  733. Yuv400 = 3,
  734. }
  735. export interface ConvertToBlobOptions {
  736. mime?: string
  737. quality?: number
  738. }
  739. export class Canvas {
  740. constructor(width: number, height: number, flag?: SvgExportFlag)
  741. width: number
  742. height: number
  743. getContext(contextType: '2d', contextAttributes?: ContextAttributes): SKRSContext2D
  744. encodeSync(format: 'webp' | 'jpeg', quality?: number): Buffer
  745. encodeSync(format: 'png'): Buffer
  746. encodeSync(format: 'avif', cfg?: AvifConfig): Buffer
  747. encodeSync(format: 'gif', quality?: number): Buffer
  748. encode(format: 'webp' | 'jpeg', quality?: number): Promise<Buffer>
  749. encode(format: 'png'): Promise<Buffer>
  750. encode(format: 'avif', cfg?: AvifConfig): Promise<Buffer>
  751. encode(format: 'gif', quality?: number): Promise<Buffer>
  752. encodeStream(format: 'webp' | 'jpeg', quality?: number): ReadableStream<Buffer>
  753. encodeStream(format: 'png'): ReadableStream<Buffer>
  754. toBuffer(mime: 'image/png'): Buffer
  755. toBuffer(mime: 'image/jpeg' | 'image/webp', quality?: number): Buffer
  756. toBuffer(mime: 'image/avif', cfg?: AvifConfig): Buffer
  757. toBuffer(mime: 'image/gif', quality?: number): Buffer
  758. // raw pixels
  759. data(): Buffer
  760. toDataURL(mime?: 'image/png'): string
  761. toDataURL(mime: 'image/jpeg' | 'image/webp', quality?: number): string
  762. toDataURL(mime: 'image/gif', quality?: number): string
  763. toDataURL(mime?: 'image/jpeg' | 'image/webp' | 'image/png' | 'image/gif', quality?: number): string
  764. toDataURL(mime?: 'image/avif', cfg?: AvifConfig): string
  765. toDataURLAsync(mime?: 'image/png'): Promise<string>
  766. toDataURLAsync(mime: 'image/jpeg' | 'image/webp', quality?: number): Promise<string>
  767. toDataURLAsync(mime: 'image/gif', quality?: number): Promise<string>
  768. toDataURLAsync(mime?: 'image/jpeg' | 'image/webp' | 'image/png' | 'image/gif', quality?: number): Promise<string>
  769. toDataURLAsync(mime?: 'image/avif', cfg?: AvifConfig): Promise<string>
  770. toBlob(callback: (blob: Blob | null) => void, mime?: string, quality?: number): void
  771. convertToBlob(options?: ConvertToBlobOptions): Promise<Blob>
  772. }
  773. export function createCanvas(width: number, height: number): Canvas
  774. export function createCanvas(width: number, height: number, svgExportFlag: SvgExportFlag): SvgCanvas
  775. export declare class FontKey {
  776. // make it a unique type
  777. private readonly key: symbol
  778. readonly typefaceId: number
  779. }
  780. export interface FontVariationAxis {
  781. /** OpenType tag as a 32-bit integer (e.g., 0x77676874 for 'wght') */
  782. tag: number
  783. /** Current value for this axis */
  784. value: number
  785. /** Minimum value for this axis */
  786. min: number
  787. /** Maximum value for this axis */
  788. max: number
  789. /** Default value for this axis */
  790. def: number
  791. /** Whether this axis should be hidden from UI */
  792. hidden: boolean
  793. }
  794. interface IGlobalFonts {
  795. readonly families: { family: string; styles: { weight: number; width: string; style: string }[] }[]
  796. // return FontKey if succeeded, null if failed
  797. register(font: Buffer, nameAlias?: string): FontKey | null
  798. // absolute path - returns FontKey if succeeded, null if failed
  799. registerFromPath(path: string, nameAlias?: string): FontKey | null
  800. has(name: string): boolean
  801. loadFontsFromDir(path: string): number
  802. /**
  803. * Set an alias for a font family.
  804. * @param fontName The original font family name
  805. * @param alias The alias name to set
  806. * @returns true if the alias was set successfully, false if the font family doesn't exist
  807. */
  808. setAlias(fontName: string, alias: string): boolean
  809. remove(key: FontKey): boolean
  810. /**
  811. * Remove multiple fonts by their keys in a single operation.
  812. * More efficient than calling remove() multiple times as it triggers only one rebuild.
  813. * @param fontKeys Array of FontKey objects to remove
  814. * @returns Number of fonts successfully removed
  815. */
  816. removeBatch(fontKeys: FontKey[]): number
  817. /**
  818. * Remove ALL registered fonts.
  819. * @returns Number of fonts removed
  820. */
  821. removeAll(): number
  822. /**
  823. * Get variation axes for a specific font instance
  824. * @param familyName The font family name
  825. * @param weight Font weight (100-900)
  826. * @param width Font width/stretch value
  827. * @param slant Font slant (0 = upright, 1 = italic, 2 = oblique)
  828. * @returns Array of variation axes or empty array if not a variable font
  829. */
  830. getVariationAxes(familyName: string, weight: number, width: number, slant: number): FontVariationAxis[]
  831. /**
  832. * Check if a font has variable font capabilities
  833. * @param familyName The font family name
  834. * @param weight Font weight (100-900)
  835. * @param width Font width/stretch value
  836. * @param slant Font slant (0 = upright, 1 = italic, 2 = oblique)
  837. * @returns true if the font is a variable font
  838. */
  839. hasVariations(familyName: string, weight: number, width: number, slant: number): boolean
  840. }
  841. export const GlobalFonts: IGlobalFonts
  842. export enum PathOp {
  843. Difference = 0, // subtract the op path from the first path
  844. Intersect = 1, // intersect the two paths
  845. Union = 2, // union (inclusive-or) the two paths
  846. Xor = 3, // exclusive-or the two paths
  847. ReverseDifference = 4, // subtract the first path from the op path
  848. }
  849. export enum FillType {
  850. Winding = 0,
  851. EvenOdd = 1,
  852. InverseWinding = 2,
  853. InverseEvenOdd = 3,
  854. }
  855. export enum StrokeJoin {
  856. Miter = 0,
  857. Round = 1,
  858. Bevel = 2,
  859. }
  860. export enum StrokeCap {
  861. Butt = 0,
  862. Round = 1,
  863. Square = 2,
  864. }
  865. export enum SvgExportFlag {
  866. ConvertTextToPaths = 0x01,
  867. NoPrettyXML = 0x02,
  868. RelativePathEncoding = 0x04,
  869. }
  870. export function convertSVGTextToPath(svg: Buffer | string): Buffer
  871. export interface LoadImageOptions {
  872. alt?: string
  873. maxRedirects?: number
  874. requestOptions?: import('http').RequestOptions
  875. }
  876. export function loadImage(
  877. source: string | URL | Buffer | ArrayBufferLike | Uint8Array | Image | import('stream').Readable,
  878. options?: LoadImageOptions,
  879. ): Promise<Image>
  880. export interface PDFMetadata {
  881. /// The document's title
  882. title?: string
  883. /// The name of the person who created the document
  884. author?: string
  885. /// The subject of the document
  886. subject?: string
  887. /// Keywords associated with the document
  888. keywords?: string
  889. /// The product that created the original document
  890. creator?: string
  891. /// The product that is converting this document to PDF (defaults to "Skia/PDF")
  892. producer?: string
  893. /// The DPI for rasterization (default: 72.0)
  894. rasterDPI?: number
  895. /// Encoding quality: 0-100 for lossy JPEG, 101 for lossless (default: 101)
  896. encodingQuality?: number
  897. /// Whether to conform to PDF/A-2b standard (default: false)
  898. pdfa?: boolean
  899. /// Compression level: -1 (default), 0 (none), 1 (low/fast), 6 (average), 9 (high/slow)
  900. compressionLevel?: number
  901. }
  902. export interface Rect {
  903. left: number
  904. top: number
  905. right: number
  906. bottom: number
  907. }
  908. export declare class PDFDocument {
  909. constructor(metadata?: PDFMetadata | undefined | null)
  910. beginPage(width: number, height: number, rect?: Rect | undefined | null): CanvasRenderingContext2D
  911. endPage(): void
  912. close(): Buffer
  913. }
  914. export interface LottieAnimationOptions {
  915. /** Base path for resolving external resources (images, fonts) */
  916. resourcePath?: string
  917. }
  918. export interface LottieRenderRect {
  919. x: number
  920. y: number
  921. width: number
  922. height: number
  923. }
  924. /**
  925. * Lottie animation class for loading and rendering Lottie JSON files.
  926. *
  927. * @example
  928. * ```typescript
  929. * import { LottieAnimation, createCanvas } from '@napi-rs/canvas'
  930. *
  931. * const animation = LottieAnimation.loadFromFile('./animation.json')
  932. * const canvas = createCanvas(animation.width, animation.height)
  933. * const ctx = canvas.getContext('2d')
  934. *
  935. * // Render frame 0
  936. * animation.seekFrame(0)
  937. * animation.render(ctx)
  938. *
  939. * // Save to PNG
  940. * const buffer = canvas.toBuffer('image/png')
  941. * ```
  942. */
  943. export declare class LottieAnimation {
  944. /**
  945. * Load animation from JSON string or Buffer
  946. * @param data - JSON string or Buffer containing Lottie animation data
  947. * @param options - Optional configuration
  948. */
  949. static loadFromData(data: string | Buffer, options?: LottieAnimationOptions): LottieAnimation
  950. /**
  951. * Load animation from file path
  952. * External assets are resolved relative to the file's directory
  953. * @param path - Path to the Lottie JSON file
  954. */
  955. static loadFromFile(path: string): LottieAnimation
  956. /** Animation duration in seconds */
  957. readonly duration: number
  958. /** Frame rate (frames per second) */
  959. readonly fps: number
  960. /** Total frame count */
  961. readonly frames: number
  962. /** Animation width in pixels */
  963. readonly width: number
  964. /** Animation height in pixels */
  965. readonly height: number
  966. /** Lottie format version string */
  967. readonly version: string
  968. /** Animation in-point (start frame) */
  969. readonly inPoint: number
  970. /** Animation out-point (end frame) */
  971. readonly outPoint: number
  972. /**
  973. * Seek to normalized position
  974. * @param t - Position between 0.0 (start) and 1.0 (end)
  975. */
  976. seek(t: number): void
  977. /**
  978. * Seek to specific frame index
  979. * @param frame - Frame index (0 = first frame)
  980. */
  981. seekFrame(frame: number): void
  982. /**
  983. * Seek to specific time in seconds
  984. * @param seconds - Time in seconds from start
  985. */
  986. seekTime(seconds: number): void
  987. /**
  988. * Render current frame to canvas context
  989. * @param ctx - Canvas 2D rendering context
  990. * @param dst - Optional destination rectangle for scaling/positioning
  991. */
  992. render(ctx: CanvasRenderingContext2D, dst?: LottieRenderRect): void
  993. }