Skip to content

Commit e79a74b

Browse files
committed
Add typescript definitions
1 parent b968c8a commit e79a74b

File tree

9 files changed

+387
-5
lines changed

9 files changed

+387
-5
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ project adheres to [Semantic Versioning](http://semver.org/).
99
==================
1010
### Changed
1111
### Added
12+
* Add typescript definitions
1213
### Fixed
1314
* PDF metadata (added in 2.3.0) wasn't being set with `canvas.createPDFStream()`
1415

Readme.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,8 @@ This is a standard API, but several non-standard calls are supported. The full l
382382
```js
383383
dataUrl = canvas.toDataURL() // defaults to PNG
384384
dataUrl = canvas.toDataURL('image/png')
385+
dataUrl = canvas.toDataURL('image/jpeg')
386+
dataUrl = canvas.toDataURL('image/jpeg', quality) // quality from 0 to 1
385387
canvas.toDataURL((err, png) => { }) // defaults to PNG
386388
canvas.toDataURL('image/png', (err, png) => { })
387389
canvas.toDataURL('image/jpeg', (err, jpeg) => { }) // sync JPEG is not supported
@@ -423,9 +425,9 @@ In `glyph` mode, `ctx.strokeText()` and `ctx.fillText()` behave the same (aside
423425
424426
This property is tracked as part of the canvas state in save/restore.
425427
426-
### CanvasRenderingContext2D#globalCompositeOperator = 'saturate'
428+
### CanvasRenderingContext2D#globalCompositeOperation = 'saturate'
427429
428-
In addition to all of the standard global composite operators defined by the Canvas specification, the ['saturate'](https://www.cairographics.org/operators/#saturate) operator is also available.
430+
In addition to all of the standard global composite operations defined by the Canvas specification, the ['saturate'](https://www.cairographics.org/operators/#saturate) operation is also available.
429431
430432
### CanvasRenderingContext2D#antialias
431433

package.json

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,11 @@
2626
"prebenchmark": "node-gyp build",
2727
"benchmark": "node benchmarks/run.js",
2828
"pretest": "standard examples/*.js test/server.js test/public/*.js benchmarks/run.js lib/context2d.js util/has_lib.js browser.js index.js && node-gyp build",
29-
"test": "mocha test/*.test.js",
29+
"test": "mocha test/*.test.js && dtslint types",
3030
"pretest-server": "node-gyp build",
3131
"test-server": "node test/server.js",
32-
"install": "node-pre-gyp install --fallback-to-build"
32+
"install": "node-pre-gyp install --fallback-to-build",
33+
"dtslint": "dtslint types"
3334
},
3435
"binary": {
3536
"module_name": "canvas",
@@ -42,14 +43,18 @@
4243
"binding.gyp",
4344
"lib/",
4445
"src/",
45-
"util/"
46+
"util/",
47+
"types/index.d.ts"
4648
],
49+
"types": "types",
4750
"dependencies": {
51+
"@types/node": "^10.12.18",
4852
"nan": "^2.12.1",
4953
"node-pre-gyp": "^0.11.0"
5054
},
5155
"devDependencies": {
5256
"assert-rejects": "^1.0.0",
57+
"dtslint": "^0.4.2",
5358
"express": "^4.16.3",
5459
"mocha": "^5.2.0",
5560
"pixelmatch": "^4.0.2",

test/testtypings.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//@ts-check
2+
3+
// This file is not executed. It can be run through the typescript compiler to
4+
// verify that the typings are working correctly.
5+
6+
const canvas = require("..")
7+
8+
let zz = new canvas.DOMMatrix()
9+
zz.a
10+
11+
canvas.registerFont("abcd", {family: "foo"})
12+
const cnv = canvas.createCanvas(10, 20)
13+
let xx = cnv.getContext("2d", {alpha: true, pixelFormat: "A8"})
14+
xx.beginPath()
15+
16+
async function foo() {
17+
const img = await canvas.loadImage("abcd");
18+
img.dataMode = canvas.Image.MODE_IMAGE
19+
};
20+
21+
cnv.toDataURL()
22+
cnv.toBuffer("image/png", {compressionLevel: 5})
23+
24+
const c2 = new canvas.Canvas(10, 10, "pdf")
25+
canvas.CanvasRenderingContext2D.prototype.globalCompositeOperation = "saturate"
26+
27+
c2.toBuffer("image/png", {resolution: 50})

types/Readme.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Notes:
2+
3+
* `"strict-export-declare-modifiers": false` because of https://github.com/Microsoft/dtslint/issues/184
4+
* `"unified-signatures": false` because of https://github.com/Microsoft/dtslint/issues/183

types/index.d.ts

Lines changed: 283 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,283 @@
1+
// TypeScript Version: 3.0
2+
/// <reference lib="dom" />
3+
4+
import { Readable } from 'stream'
5+
6+
export interface PngConfig {
7+
/** defaults to 6 */
8+
compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
9+
/** defaults to `canvas.PNG_ALL_FITLERS` */
10+
filters?: number
11+
/** _For creating indexed PNGs._ The palette of colors. */
12+
palette?: Uint8ClampedArray
13+
/** _For creating indexed PNGs._ The index of the background color. */
14+
backgroundIndex?: number
15+
/** pixels per inch */
16+
resolution?: number
17+
}
18+
19+
export interface JpegConfig {
20+
/** defaults to 0.75 */
21+
quality?: number
22+
/** defautls to false */
23+
progressive?: boolean
24+
/** defaults to true */
25+
chromaSubsampling?: boolean
26+
}
27+
28+
export interface PdfConfig {
29+
title?: string
30+
author?: string
31+
subject?: string
32+
keywords?: string
33+
creator?: string
34+
creationDate?: Date
35+
modDate?: Date
36+
}
37+
38+
export interface NodeCanvasRenderingContext2DSettings {
39+
alpha?: boolean
40+
pixelFormat?: 'RGBA32' | 'RGB24' | 'A8' | 'RGB16_565' | 'A1' | 'RGB30'
41+
}
42+
43+
export class Canvas {
44+
constructor(width: number, height: number, type?: 'pdf'|'svg')
45+
46+
getContext(contextId: '2d', contextAttributes?: NodeCanvasRenderingContext2DSettings): NodeCanvasRenderingContext2D
47+
48+
/**
49+
* For image canvases, encodes the canvas as a PNG. For PDF canvases,
50+
* encodes the canvas as a PDF. For SVG canvases, encodes the canvas as an
51+
* SVG.
52+
*/
53+
toBuffer(cb: (err: Error|null, result: Buffer) => void): void
54+
toBuffer(cb: (err: Error|null, result: Buffer) => void, mimeType: 'image/png', config?: PngConfig): void
55+
toBuffer(cb: (err: Error|null, result: Buffer) => void, mimeType: 'image/jpeg', config?: JpegConfig): void
56+
57+
/**
58+
* For image canvases, encodes the canvas as a PNG. For PDF canvases,
59+
* encodes the canvas as a PDF. For SVG canvases, encodes the canvas as an
60+
* SVG.
61+
*/
62+
toBuffer(): Buffer
63+
toBuffer(mimeType: 'image/png', config?: PngConfig): Buffer
64+
toBuffer(mimeType: 'image/jpeg', config?: JpegConfig): Buffer
65+
toBuffer(mimeType: 'application/pdf', config?: PdfConfig): Buffer
66+
67+
/**
68+
* Returns the raw ARGB data without encoding in native-endian byte order,
69+
* top-to-bottom.
70+
*/
71+
toBuffer(mimeType: 'raw'): Buffer
72+
73+
createPNGStream(config?: PngConfig): Readable
74+
createJPEGStream(config?: JpegConfig): Readable
75+
createPDFStream(config?: PdfConfig): Readable
76+
77+
/** Defaults to PNG image. */
78+
toDataURL(): string
79+
toDataURL(mimeType: 'image/png'): string
80+
toDataURL(mimeType: 'image/jpeg', quality?: number): string
81+
/** _Non-standard._ Defaults to PNG image. */
82+
toDataURL(cb: (err: Error|null, result: string) => void): void
83+
/** _Non-standard._ */
84+
toDataURL(mimeType: 'image/png', cb: (err: Error|null, result: string) => void): void
85+
/** _Non-standard._ */
86+
toDataURL(mimeType: 'image/jpeg', cb: (err: Error|null, result: string) => void): void
87+
/** _Non-standard._ */
88+
toDataURL(mimeType: 'image/jpeg', config: JpegConfig, cb: (err: Error|null, result: string) => void): void
89+
/** _Non-standard._ */
90+
toDataURL(mimeType: 'image/jpeg', quality: number, cb: (err: Error|null, result: string) => void): void
91+
92+
/**
93+
* For PDF canvases, adds another page. If width and/or height are omitted,
94+
* the canvas's initial size is used.
95+
*/
96+
addPage(width?: number, height?: number): void
97+
}
98+
99+
declare class NodeCanvasRenderingContext2D extends CanvasRenderingContext2D {
100+
/**
101+
* _Non-standard_. Defaults to 'good'. Affects pattern (gradient, image,
102+
* etc.) rendering quality.
103+
*/
104+
patternQuality: 'fast' | 'good' | 'best' | 'nearest' | 'bilinear'
105+
106+
/**
107+
* _Non-standard_. Defaults to 'good'. Like `patternQuality`, but applies to
108+
* transformations affecting more than just patterns.
109+
*/
110+
quality: 'fast' | 'good' | 'best' | 'nearest' | 'bilinear'
111+
112+
/**
113+
* Defaults to 'path'. The effect depends on the canvas type:
114+
*
115+
* * **Standard (image)** `'glyph'` and `'path'` both result in rasterized
116+
* text. Glyph mode is faster than path, but may result in lower-quality
117+
* text, especially when rotated or translated.
118+
*
119+
* * **PDF** `'glyph'` will embed text instead of paths into the PDF. This
120+
* is faster to encode, faster to open with PDF viewers, yields a smaller
121+
* file size and makes the text selectable. The subset of the font needed
122+
* to render the glyphs will be embedded in the PDF. This is usually the
123+
* mode you want to use with PDF canvases.
124+
*
125+
* * **SVG** glyph does not cause `<text>` elements to be produced as one
126+
* might expect ([cairo bug](https://gitlab.freedesktop.org/cairo/cairo/issues/253)).
127+
* Rather, glyph will create a `<defs>` section with a `<symbol>` for each
128+
* glyph, then those glyphs be reused via `<use>` elements. `'path'` mode
129+
* creates a `<path>` element for each text string. glyph mode is faster
130+
* and yields a smaller file size.
131+
*
132+
* In glyph mode, `ctx.strokeText()` and `ctx.fillText()` behave the same
133+
* (aside from using the stroke and fill style, respectively).
134+
*/
135+
textDrawingMode: 'path' | 'glyph'
136+
137+
/** _'saturate' is non-standard._ */
138+
globalCompositeOperation: 'saturate' | 'clear' | 'copy' | 'destination' | 'source-over' | 'destination-over' |
139+
'source-in' | 'destination-in' | 'source-out' | 'destination-out' | 'source-atop' | 'destination-atop' |
140+
'xor' | 'lighter' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' |
141+
'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity'
142+
143+
/** _Non-standard_. Sets the antialiasing mode. */
144+
antialias: 'default' | 'gray' | 'none' | 'subpixel'
145+
146+
// Standard, but not in the TS lib.
147+
/** Returns or sets a `DOMMatrix` for the current transformation matrix. */
148+
currentTransform: NodeCanvasDOMMatrix
149+
150+
// Standard, but need node-canvas class versions:
151+
getTransform(): NodeCanvasDOMMatrix
152+
setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void
153+
setTransform(transform?: NodeCanvasDOMMatrix): void
154+
createImageData(sw: number, sh: number): NodeCanvasImageData;
155+
createImageData(imagedata: NodeCanvasImageData): NodeCanvasImageData;
156+
getImageData(sx: number, sy: number, sw: number, sh: number): NodeCanvasImageData;
157+
putImageData(imagedata: NodeCanvasImageData, dx: number, dy: number): void;
158+
putImageData(imagedata: NodeCanvasImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void;
159+
}
160+
export { NodeCanvasRenderingContext2D as CanvasRenderingContext2D }
161+
162+
declare class NodeCanvasCanvasGradient extends CanvasGradient {}
163+
export { NodeCanvasCanvasGradient as CanvasGradient }
164+
165+
declare class NodeCanvasCanvasPattern extends CanvasPattern {}
166+
export { NodeCanvasCanvasPattern as CanvasPattern }
167+
168+
// This does not extend HTMLImageElement because there are dozens of inherited
169+
// methods and properties that we do not provide.
170+
export class Image {
171+
/** Track image data */
172+
static readonly MODE_IMAGE: number
173+
/** Track MIME data */
174+
static readonly MODE_MIME: number
175+
176+
/**
177+
* The URL or local file path of the image to be loaded, or a Buffer
178+
* instance containing an encoded image.
179+
*/
180+
src: string | Buffer
181+
/** Retrieves whether the object is fully loaded. */
182+
readonly complete: boolean
183+
/** Sets or retrieves the height of the image. */
184+
height: number
185+
/** Sets or retrieves the width of the image. */
186+
width: number
187+
188+
/** The original height of the image resource before sizing. */
189+
readonly naturalHeight: number;
190+
/** The original width of the image resource before sizing. */
191+
readonly naturalWidth: number;
192+
/**
193+
* Applies to JPEG images drawn to PDF canvases only. Setting
194+
* `img.dataMode = Image.MODE_MIME` or `Image.MODE_MIME|Image.MODE_IMAGE`
195+
* enables image MIME data tracking. When MIME data is tracked, PDF canvases
196+
* can embed JPEGs directly into the output, rather than re-encoding into
197+
* PNG. This can drastically reduce filesize and speed up rendering.
198+
*/
199+
dataMode: number
200+
201+
onload(): void
202+
onerror(err: Error): void
203+
}
204+
205+
/**
206+
* Creates a Canvas instance. This function works in both Node.js and Web
207+
* browsers, where there is no Canvas constructor.
208+
* @param type Optionally specify to create a PDF or SVG canvas. Defaults to an
209+
* image canvas.
210+
*/
211+
export function createCanvas(width: number, height: number, type?: 'pdf'|'svg'): Canvas
212+
213+
/**
214+
* Creates an ImageData instance. This function works in both Node.js and Web
215+
* browsers.
216+
* @param data An array containing the pixel representation of the image.
217+
* @param height If omitted, the height is calculated based on the array's size
218+
* and `width`.
219+
*/
220+
export function createImageData(data: Uint8ClampedArray, width: number, height?: number): ImageData
221+
/**
222+
* _Non-standard._ Creates an ImageData instance for an alternative pixel
223+
* format, such as RGB16_565
224+
* @param data An array containing the pixel representation of the image.
225+
* @param height If omitted, the height is calculated based on the array's size
226+
* and `width`.
227+
*/
228+
export function createImageData(data: Uint16Array, width: number, height?: number): ImageData
229+
/**
230+
* Creates an ImageData instance. This function works in both Node.js and Web
231+
* browsers.
232+
*/
233+
export function createImageData(width: number, height: number): ImageData
234+
235+
/**
236+
* Convenience function for loading an image with a Promise interface. This
237+
* function works in both Node.js and Web browsers; however, the `src` must be
238+
* a string in Web browsers (it can only be a Buffer in Node.js).
239+
* @param src URL, `data: ` URI or (Node.js only) a local file path or Buffer
240+
* instance.
241+
*/
242+
export function loadImage(src: string|Buffer): Promise<Image>
243+
244+
/**
245+
* Registers a font that is not installed as a system font. This must be used
246+
* before creating Canvas instances.
247+
* @param path Path to local font file.
248+
* @param fontFace Description of the font face, corresponding to CSS properties
249+
* used in `@font-face` rules.
250+
*/
251+
export function registerFont(path: string, fontFace: {family: string, weight?: string, style?: string}): void
252+
253+
/** This class must not be constructed directly; use `canvas.createPNGStream()`. */
254+
export class PNGStream extends Readable {}
255+
/** This class must not be constructed directly; use `canvas.createJPEGStream()`. */
256+
export class JPEGStream extends Readable {}
257+
/** This class must not be constructed directly; use `canvas.createPDFStream()`. */
258+
export class PDFStream extends Readable {}
259+
260+
declare class NodeCanvasDOMMatrix extends DOMMatrix {}
261+
export { NodeCanvasDOMMatrix as DOMMatrix }
262+
263+
declare class NodeCanvasDOMPoint extends DOMPoint {}
264+
export { NodeCanvasDOMPoint as DOMPoint }
265+
266+
declare class NodeCanvasImageData extends ImageData {}
267+
export { NodeCanvasImageData as ImageData }
268+
269+
// This is marked private, but is exported...
270+
// export function parseFont(description: string): object
271+
272+
// Not documented: backends
273+
274+
/** Library version. */
275+
export const version: string
276+
/** Cairo version. */
277+
export const cairoVersion: string
278+
/** jpeglib version, if built with JPEG support. */
279+
export const jpegVersion: string | undefined
280+
/** giflib version, if built with GIF support. */
281+
export const gifVersion: string | undefined
282+
/** freetype version. */
283+
export const freetypeVersion: string

0 commit comments

Comments
 (0)