From fabfac9c621fae371bcfcb126a7255ccbbee6214 Mon Sep 17 00:00:00 2001 From: Zach Bjornson Date: Fri, 14 Dec 2018 20:37:58 -0800 Subject: [PATCH] Add typescript definitions --- .travis.yml | 3 + CHANGELOG.md | 1 + Readme.md | 6 +- lib/canvas.js | 69 --------- lib/jpegstream.js | 20 --- lib/pdfstream.js | 20 --- lib/pngstream.js | 9 -- package.json | 9 +- types/Readme.md | 3 + types/index.d.ts | 338 ++++++++++++++++++++++++++++++++++++++++++++ types/test.ts | 42 ++++++ types/tsconfig.json | 13 ++ types/tslint.json | 7 + 13 files changed, 418 insertions(+), 122 deletions(-) create mode 100644 types/Readme.md create mode 100644 types/index.d.ts create mode 100644 types/test.ts create mode 100644 types/tsconfig.json create mode 100644 types/tslint.json diff --git a/.travis.yml b/.travis.yml index e7e3fca5f..a5d413ae5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,3 +19,6 @@ addons: env: - CXX=g++-4.9 sudo: false +script: + - node_version=$(node -v); if [ ${node_version:1:2} = 10 ]; then npm run dtslint; fi + - npm test diff --git a/CHANGELOG.md b/CHANGELOG.md index 314a136ef..219e7630d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ project adheres to [Semantic Versioning](http://semver.org/). ### Added * (Actually) added `resolution` option for `canvas.toBuffer("image/png")` and `canvas.createPNGStream()`. This was documented since 2.0.0 but not working. +* Add typescript definitions. ### Fixed * PDF metadata (added in 2.3.0) wasn't being set with `canvas.createPDFStream()` * Fix custom "inspect" function deprecation warnings (#1326) diff --git a/Readme.md b/Readme.md index 9d037ce9d..52f4afb67 100644 --- a/Readme.md +++ b/Readme.md @@ -382,6 +382,8 @@ This is a standard API, but several non-standard calls are supported. The full l ```js dataUrl = canvas.toDataURL() // defaults to PNG dataUrl = canvas.toDataURL('image/png') +dataUrl = canvas.toDataURL('image/jpeg') +dataUrl = canvas.toDataURL('image/jpeg', quality) // quality from 0 to 1 canvas.toDataURL((err, png) => { }) // defaults to PNG canvas.toDataURL('image/png', (err, png) => { }) 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 This property is tracked as part of the canvas state in save/restore. -### CanvasRenderingContext2D#globalCompositeOperator = 'saturate' +### CanvasRenderingContext2D#globalCompositeOperation = 'saturate' -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. +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. ### CanvasRenderingContext2D#antialias diff --git a/lib/canvas.js b/lib/canvas.js index 2ba013f65..3f48ba65d 100644 --- a/lib/canvas.js +++ b/lib/canvas.js @@ -6,10 +6,6 @@ * MIT Licensed */ -/** - * Module dependencies. - */ - const bindings = require('./bindings') const Canvas = module.exports = bindings.Canvas const Context2d = require('./context2d') @@ -24,15 +20,6 @@ Canvas.prototype[util.inspect.custom || 'inspect'] = function () { return `[Canvas ${this.width}x${this.height}]` } -/** - * Get a context object. - * - * @param {String} contextType must be "2d" - * @param {Object {alpha: boolean, pixelFormat: PIXEL_FORMAT} } contextAttributes Optional - * @return {Context2d} - * @api public - */ - Canvas.prototype.getContext = function (contextType, contextAttributes) { if ('2d' == contextType) { var ctx = this._context2d || (this._context2d = new Context2d(this, contextAttributes)); @@ -42,77 +29,21 @@ Canvas.prototype.getContext = function (contextType, contextAttributes) { } }; -/** - * Create a `PNGStream` for `this` canvas. - * - * @param {Object} [options] - * @param {number} [options.compressionLevel] Number from 0 to 9 corresponding - * to the ZLIB compression level. Defaults to 6. - * @param {number} [options.filters] Any bitwise combination of - * `PNG_FILTER_NONE`, `PNG_FITLER_SUB`, `PNG_FILTER_UP`, `PNG_FILTER_AVG`, - * `PNG_FILTER_PATETH`; or one of `PNG_ALL_FILTERS` or `PNG_NO_FILTERS`. These - * specify which filters *may* be used by libpng. During encoding, libpng will - * select the best filter from this list of allowed filters. - * @param {Uint8ClampedArray} [options.palette] Provide for indexed PNG - * encoding. Entries should be R-G-B-A values. - * @param {number} [options.backgroundIndex] Optional index of background color - * for indexed PNGs. Defaults to 0. - * @return {PNGStream} - * @public - */ Canvas.prototype.pngStream = Canvas.prototype.createPNGStream = function(options){ return new PNGStream(this, options); }; -/** - * Create a `PDFStream` for `this` canvas. - * - * @param {object} [options] - * @param {string} [options.title] - * @param {string} [options.author] - * @param {string} [options.subject] - * @param {string} [options.keywords] - * @param {string} [options.creator] - * @param {Date} [options.creationDate] - * @param {Date} [options.modDate] - * @return {PDFStream} - * @public - */ Canvas.prototype.pdfStream = Canvas.prototype.createPDFStream = function(options){ return new PDFStream(this, options); }; -/** - * Create a `JPEGStream` for `this` canvas. - * - * @param {Object} [options] - * @param {number} [options.quality] Number from 0 to 1. Defaults to 0.75. - * @param {boolean|1|2} [options.chromaSubsampling] Enables 2x2 chroma - * subsampling. `true` is equivalent to `2`, `false` is equivalent to `1`. - * @param {boolean} [options.progressive] Enables progressive encoding. Defautls - * to false. - * @return {JPEGStream} - * @public - */ Canvas.prototype.jpegStream = Canvas.prototype.createJPEGStream = function(options){ return new JPEGStream(this, options); }; -/** - * Returns a data URI. Pass a function for async operation (non-standard). - * - * @param {"image/png"|"image/jpeg"} [type="image/png"] Type. - * @param {Object|Number} [encoderOptions] A number between 0 and 1 indicating - * image quality if the requested type is image/jpeg (standard), or an options - * object for image encoding (see documentation for Canvas#toBuffer) - * (non-standard). - * @param {Function} [fn] Callback for asynchronous operation (non-standard). - * @return {String} data URL if synchronous (callback omitted) - * @api public - */ Canvas.prototype.toDataURL = function(a1, a2, a3){ // valid arg patterns (args -> [type, opts, fn]): // [] -> ['image/png', null, null] diff --git a/lib/jpegstream.js b/lib/jpegstream.js index e44ed4c65..a057d8983 100644 --- a/lib/jpegstream.js +++ b/lib/jpegstream.js @@ -6,29 +6,9 @@ * MIT Licensed */ -/** - * Module dependencies. - */ - var Readable = require('stream').Readable; var util = require('util'); -/** - * Initialize a `JPEGStream` with the given `canvas`. - * - * "data" events are emitted with `Buffer` chunks, once complete the - * "end" event is emitted. The following example will stream to a file - * named "./my.jpeg". - * - * var out = fs.createWriteStream(__dirname + '/my.jpeg') - * , stream = canvas.createJPEGStream(); - * - * stream.pipe(out); - * - * @param {Canvas} canvas - * @private - */ - var JPEGStream = module.exports = function JPEGStream(canvas, options) { if (!(this instanceof JPEGStream)) { throw new TypeError("Class constructors cannot be invoked without 'new'"); diff --git a/lib/pdfstream.js b/lib/pdfstream.js index 99229703b..6aeec53d7 100644 --- a/lib/pdfstream.js +++ b/lib/pdfstream.js @@ -4,29 +4,9 @@ * Canvas - PDFStream */ -/** - * Module dependencies. - */ - var Readable = require('stream').Readable; var util = require('util'); -/** - * Initialize a `PDFStream` with the given `canvas`. - * - * "data" events are emitted with `Buffer` chunks, once complete the - * "end" event is emitted. The following example will stream to a file - * named "./my.pdf". - * - * var out = fs.createWriteStream(__dirname + '/my.pdf') - * , stream = canvas.createPDFStream(); - * - * stream.pipe(out); - * - * @param {Canvas} canvas - * @api public - */ - var PDFStream = module.exports = function PDFStream(canvas, options) { if (!(this instanceof PDFStream)) { throw new TypeError("Class constructors cannot be invoked without 'new'"); diff --git a/lib/pngstream.js b/lib/pngstream.js index 3a03c78c7..021bb7fd9 100644 --- a/lib/pngstream.js +++ b/lib/pngstream.js @@ -6,18 +6,9 @@ * MIT Licensed */ -/** - * Module dependencies. - */ - var Readable = require('stream').Readable; var util = require('util'); -/** - * @param {Canvas} canvas - * @param {Object} options - * @private - */ var PNGStream = module.exports = function PNGStream(canvas, options) { if (!(this instanceof PNGStream)) { throw new TypeError("Class constructors cannot be invoked without 'new'"); diff --git a/package.json b/package.json index 4631aa33e..3e434db1c 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,8 @@ "test": "mocha test/*.test.js", "pretest-server": "node-gyp build", "test-server": "node test/server.js", - "install": "node-pre-gyp install --fallback-to-build" + "install": "node-pre-gyp install --fallback-to-build", + "dtslint": "dtslint types" }, "binary": { "module_name": "canvas", @@ -42,14 +43,18 @@ "binding.gyp", "lib/", "src/", - "util/" + "util/", + "types/index.d.ts" ], + "types": "types", "dependencies": { "nan": "^2.12.1", "node-pre-gyp": "^0.11.0" }, "devDependencies": { + "@types/node": "^10.12.18", "assert-rejects": "^1.0.0", + "dtslint": "^0.5.3", "express": "^4.16.3", "mocha": "^5.2.0", "pixelmatch": "^4.0.2", diff --git a/types/Readme.md b/types/Readme.md new file mode 100644 index 000000000..4beb7f528 --- /dev/null +++ b/types/Readme.md @@ -0,0 +1,3 @@ +Notes: + +* `"unified-signatures": false` because of https://github.com/Microsoft/dtslint/issues/183 diff --git a/types/index.d.ts b/types/index.d.ts new file mode 100644 index 000000000..e190da16e --- /dev/null +++ b/types/index.d.ts @@ -0,0 +1,338 @@ +// TypeScript Version: 3.0 +/// + +import { Readable } from 'stream' + +export interface PngConfig { + /** Specifies the ZLIB compression level. Defaults to 6. */ + compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 + /** + * Any bitwise combination of `PNG_FILTER_NONE`, `PNG_FITLER_SUB`, + * `PNG_FILTER_UP`, `PNG_FILTER_AVG` and `PNG_FILTER_PATETH`; or one of + * `PNG_ALL_FILTERS` or `PNG_NO_FILTERS` (all are properties of the canvas + * instance). These specify which filters *may* be used by libpng. During + * encoding, libpng will select the best filter from this list of allowed + * filters. Defaults to `canvas.PNG_ALL_FITLERS`. + */ + filters?: number + /** + * _For creating indexed PNGs._ The palette of colors. Entries should be in + * RGBA order. + */ + palette?: Uint8ClampedArray + /** + * _For creating indexed PNGs._ The index of the background color. Defaults + * to 0. + */ + backgroundIndex?: number + /** pixels per inch */ + resolution?: number +} + +export interface JpegConfig { + /** Specifies the quality, between 0 and 1. Defaults to 0.75. */ + quality?: number + /** Enables progressive encoding. Defaults to `false`. */ + progressive?: boolean + /** Enables 2x2 chroma subsampling. Defaults to `true`. */ + chromaSubsampling?: boolean +} + +export interface PdfConfig { + title?: string + author?: string + subject?: string + keywords?: string + creator?: string + creationDate?: Date + modDate?: Date +} + +export interface NodeCanvasRenderingContext2DSettings { + alpha?: boolean + pixelFormat?: 'RGBA32' | 'RGB24' | 'A8' | 'RGB16_565' | 'A1' | 'RGB30' +} + +export class Canvas { + width: number + height: number + + /** _Non standard._ The type of the canvas. */ + readonly type: 'image'|'pdf'|'svg' + + // This is a getter, but it's non-standard and I don't know why we export it. + // readonly stride: number; + + /** Constant used in PNG encoding methods. */ + readonly PNG_NO_FILTERS: number + /** Constant used in PNG encoding methods. */ + readonly PNG_ALL_FILTERS: number + /** Constant used in PNG encoding methods. */ + readonly PNG_FILTER_NONE: number + /** Constant used in PNG encoding methods. */ + readonly PNG_FILTER_SUB: number + /** Constant used in PNG encoding methods. */ + readonly PNG_FILTER_UP: number + /** Constant used in PNG encoding methods. */ + readonly PNG_FILTER_AVG: number + /** Constant used in PNG encoding methods. */ + readonly PNG_FILTER_PAETH: number + + constructor(width: number, height: number, type?: 'pdf'|'svg') + + getContext(contextId: '2d', contextAttributes?: NodeCanvasRenderingContext2DSettings): NodeCanvasRenderingContext2D + + /** + * For image canvases, encodes the canvas as a PNG. For PDF canvases, + * encodes the canvas as a PDF. For SVG canvases, encodes the canvas as an + * SVG. + */ + toBuffer(cb: (err: Error|null, result: Buffer) => void): void + toBuffer(cb: (err: Error|null, result: Buffer) => void, mimeType: 'image/png', config?: PngConfig): void + toBuffer(cb: (err: Error|null, result: Buffer) => void, mimeType: 'image/jpeg', config?: JpegConfig): void + + /** + * For image canvases, encodes the canvas as a PNG. For PDF canvases, + * encodes the canvas as a PDF. For SVG canvases, encodes the canvas as an + * SVG. + */ + toBuffer(): Buffer + toBuffer(mimeType: 'image/png', config?: PngConfig): Buffer + toBuffer(mimeType: 'image/jpeg', config?: JpegConfig): Buffer + toBuffer(mimeType: 'application/pdf', config?: PdfConfig): Buffer + + /** + * Returns the raw ARGB data without encoding in native-endian byte order, + * top-to-bottom. + */ + toBuffer(mimeType: 'raw'): Buffer + + createPNGStream(config?: PngConfig): PNGStream + createJPEGStream(config?: JpegConfig): JPEGStream + createPDFStream(config?: PdfConfig): PDFStream + + /** Defaults to PNG image. */ + toDataURL(): string + toDataURL(mimeType: 'image/png'): string + toDataURL(mimeType: 'image/jpeg', quality?: number): string + /** _Non-standard._ Defaults to PNG image. */ + toDataURL(cb: (err: Error|null, result: string) => void): void + /** _Non-standard._ */ + toDataURL(mimeType: 'image/png', cb: (err: Error|null, result: string) => void): void + /** _Non-standard._ */ + toDataURL(mimeType: 'image/jpeg', cb: (err: Error|null, result: string) => void): void + /** _Non-standard._ */ + toDataURL(mimeType: 'image/jpeg', config: JpegConfig, cb: (err: Error|null, result: string) => void): void + /** _Non-standard._ */ + toDataURL(mimeType: 'image/jpeg', quality: number, cb: (err: Error|null, result: string) => void): void + + /** + * For PDF canvases, adds another page. If width and/or height are omitted, + * the canvas's initial size is used. + */ + addPage(width?: number, height?: number): void +} + +declare class NodeCanvasRenderingContext2D extends CanvasRenderingContext2D { + /** + * _Non-standard_. Defaults to 'good'. Affects pattern (gradient, image, + * etc.) rendering quality. + */ + patternQuality: 'fast' | 'good' | 'best' | 'nearest' | 'bilinear' + + /** + * _Non-standard_. Defaults to 'good'. Like `patternQuality`, but applies to + * transformations affecting more than just patterns. + */ + quality: 'fast' | 'good' | 'best' | 'nearest' | 'bilinear' + + /** + * Defaults to 'path'. The effect depends on the canvas type: + * + * * **Standard (image)** `'glyph'` and `'path'` both result in rasterized + * text. Glyph mode is faster than path, but may result in lower-quality + * text, especially when rotated or translated. + * + * * **PDF** `'glyph'` will embed text instead of paths into the PDF. This + * is faster to encode, faster to open with PDF viewers, yields a smaller + * file size and makes the text selectable. The subset of the font needed + * to render the glyphs will be embedded in the PDF. This is usually the + * mode you want to use with PDF canvases. + * + * * **SVG** glyph does not cause `` elements to be produced as one + * might expect ([cairo bug](https://gitlab.freedesktop.org/cairo/cairo/issues/253)). + * Rather, glyph will create a `` section with a `` for each + * glyph, then those glyphs be reused via `` elements. `'path'` mode + * creates a `` element for each text string. glyph mode is faster + * and yields a smaller file size. + * + * In glyph mode, `ctx.strokeText()` and `ctx.fillText()` behave the same + * (aside from using the stroke and fill style, respectively). + */ + textDrawingMode: 'path' | 'glyph' + + /** _'saturate' is non-standard._ */ + globalCompositeOperation: 'saturate' | 'clear' | 'copy' | 'destination' | 'source-over' | 'destination-over' | + 'source-in' | 'destination-in' | 'source-out' | 'destination-out' | 'source-atop' | 'destination-atop' | + 'xor' | 'lighter' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' | + 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity' + + /** _Non-standard_. Sets the antialiasing mode. */ + antialias: 'default' | 'gray' | 'none' | 'subpixel' + + // Standard, but not in the TS lib and needs node-canvas class return type. + /** Returns or sets a `DOMMatrix` for the current transformation matrix. */ + currentTransform: NodeCanvasDOMMatrix + + // Standard, but need node-canvas class versions: + getTransform(): NodeCanvasDOMMatrix + setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void + setTransform(transform?: NodeCanvasDOMMatrix): void + createImageData(sw: number, sh: number): NodeCanvasImageData + createImageData(imagedata: NodeCanvasImageData): NodeCanvasImageData + getImageData(sx: number, sy: number, sw: number, sh: number): NodeCanvasImageData + putImageData(imagedata: NodeCanvasImageData, dx: number, dy: number): void + putImageData(imagedata: NodeCanvasImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void + drawImage(image: Canvas|Image, dx: number, dy: number): void + drawImage(image: Canvas|Image, dx: number, dy: number, dw: number, dh: number): void + drawImage(image: Canvas|Image, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void + /** + * **Do not use this overload. Use one of the other three overloads.** This + * is a catch-all definition required for compatibility with the base + * `CanvasRenderingContext2D` interface. + */ + drawImage(...args: any[]): void + createPattern(image: Canvas|Image, repetition: 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat' | '' | null): NodeCanvasCanvasPattern + /** + * **Do not use this overload. Use the other three overload.** This is a + * catch-all definition required for compatibility with the base + * `CanvasRenderingContext2D` interface. + */ + createPattern(...args: any[]): NodeCanvasCanvasPattern + createLinearGradient(x0: number, y0: number, x1: number, y1: number): NodeCanvasCanvasGradient; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): NodeCanvasCanvasGradient; +} +export { NodeCanvasRenderingContext2D as CanvasRenderingContext2D } + +declare class NodeCanvasCanvasGradient extends CanvasGradient {} +export { NodeCanvasCanvasGradient as CanvasGradient } + +declare class NodeCanvasCanvasPattern extends CanvasPattern {} +export { NodeCanvasCanvasPattern as CanvasPattern } + +// This does not extend HTMLImageElement because there are dozens of inherited +// methods and properties that we do not provide. +export class Image { + /** Track image data */ + static readonly MODE_IMAGE: number + /** Track MIME data */ + static readonly MODE_MIME: number + + /** + * The URL, `data:` URI or local file path of the image to be loaded, or a + * Buffer instance containing an encoded image. + */ + src: string | Buffer + /** Retrieves whether the object is fully loaded. */ + readonly complete: boolean + /** Sets or retrieves the height of the image. */ + height: number + /** Sets or retrieves the width of the image. */ + width: number + + /** The original height of the image resource before sizing. */ + readonly naturalHeight: number + /** The original width of the image resource before sizing. */ + readonly naturalWidth: number + /** + * Applies to JPEG images drawn to PDF canvases only. Setting + * `img.dataMode = Image.MODE_MIME` or `Image.MODE_MIME|Image.MODE_IMAGE` + * enables image MIME data tracking. When MIME data is tracked, PDF canvases + * can embed JPEGs directly into the output, rather than re-encoding into + * PNG. This can drastically reduce filesize and speed up rendering. + */ + dataMode: number + + onload: (() => void) | null; + onerror: ((err: Error) => void) | null; +} + +/** + * Creates a Canvas instance. This function works in both Node.js and Web + * browsers, where there is no Canvas constructor. + * @param type Optionally specify to create a PDF or SVG canvas. Defaults to an + * image canvas. + */ +export function createCanvas(width: number, height: number, type?: 'pdf'|'svg'): Canvas + +/** + * Creates an ImageData instance. This function works in both Node.js and Web + * browsers. + * @param data An array containing the pixel representation of the image. + * @param height If omitted, the height is calculated based on the array's size + * and `width`. + */ +export function createImageData(data: Uint8ClampedArray, width: number, height?: number): ImageData +/** + * _Non-standard._ Creates an ImageData instance for an alternative pixel + * format, such as RGB16_565 + * @param data An array containing the pixel representation of the image. + * @param height If omitted, the height is calculated based on the array's size + * and `width`. + */ +export function createImageData(data: Uint16Array, width: number, height?: number): ImageData +/** + * Creates an ImageData instance. This function works in both Node.js and Web + * browsers. + */ +export function createImageData(width: number, height: number): ImageData + +/** + * Convenience function for loading an image with a Promise interface. This + * function works in both Node.js and Web browsers; however, the `src` must be + * a string in Web browsers (it can only be a Buffer in Node.js). + * @param src URL, `data: ` URI or (Node.js only) a local file path or Buffer + * instance. + */ +export function loadImage(src: string|Buffer): Promise + +/** + * Registers a font that is not installed as a system font. This must be used + * before creating Canvas instances. + * @param path Path to local font file. + * @param fontFace Description of the font face, corresponding to CSS properties + * used in `@font-face` rules. + */ +export function registerFont(path: string, fontFace: {family: string, weight?: string, style?: string}): void + +/** This class must not be constructed directly; use `canvas.createPNGStream()`. */ +export class PNGStream extends Readable {} +/** This class must not be constructed directly; use `canvas.createJPEGStream()`. */ +export class JPEGStream extends Readable {} +/** This class must not be constructed directly; use `canvas.createPDFStream()`. */ +export class PDFStream extends Readable {} + +declare class NodeCanvasDOMMatrix extends DOMMatrix {} +export { NodeCanvasDOMMatrix as DOMMatrix } + +declare class NodeCanvasDOMPoint extends DOMPoint {} +export { NodeCanvasDOMPoint as DOMPoint } + +declare class NodeCanvasImageData extends ImageData {} +export { NodeCanvasImageData as ImageData } + +// This is marked private, but is exported... +// export function parseFont(description: string): object + +// Not documented: backends + +/** Library version. */ +export const version: string +/** Cairo version. */ +export const cairoVersion: string +/** jpeglib version, if built with JPEG support. */ +export const jpegVersion: string | undefined +/** giflib version, if built with GIF support. */ +export const gifVersion: string | undefined +/** freetype version. */ +export const freetypeVersion: string diff --git a/types/test.ts b/types/test.ts new file mode 100644 index 000000000..8cff19419 --- /dev/null +++ b/types/test.ts @@ -0,0 +1,42 @@ +import * as Canvas from 'canvas' + +Canvas.createCanvas(5, 10) +Canvas.createCanvas(200, 200, 'pdf') +Canvas.createCanvas(150, 150, 'svg') + +const canv = Canvas.createCanvas(10, 10) +const ctx = canv.getContext('2d') +canv.getContext('2d', {alpha: false}) + +// LHS is ImageData, not Canvas.ImageData +const id = ctx.getImageData(0, 0, 10, 10) +const h: number = id.height + +ctx.currentTransform = ctx.getTransform() + +ctx.quality = 'best' +ctx.textDrawingMode = 'glyph' +ctx.globalCompositeOperation = 'saturate' + +const grad: Canvas.CanvasGradient = ctx.createLinearGradient(0, 1, 2, 3) +grad.addColorStop(0.1, 'red') + +const dm = new Canvas.DOMMatrix([1, 2, 3, 4, 5, 6]) +const a: number = dm.a + +const b1: Buffer = canv.toBuffer() +canv.toBuffer("application/pdf") +canv.toBuffer((err, data) => {}, "image/png") +canv.createJPEGStream({quality: 0.5}) +canv.createPDFStream({author: "octocat"}) +canv.toDataURL() + +const img = new Canvas.Image() +img.src = Buffer.alloc(0) +img.dataMode = Canvas.Image.MODE_IMAGE | Canvas.Image.MODE_MIME +img.onload = () => {} +img.onload = null; + +const id2: Canvas.ImageData = Canvas.createImageData(new Uint16Array(4), 1) + +ctx.drawImage(canv, 0, 0) diff --git a/types/tsconfig.json b/types/tsconfig.json new file mode 100644 index 000000000..226482c23 --- /dev/null +++ b/types/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noEmit": true, + "baseUrl": ".", + "paths": { "canvas": ["."] } + } +} diff --git a/types/tslint.json b/types/tslint.json new file mode 100644 index 000000000..64e2a316f --- /dev/null +++ b/types/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dtslint.json", + "rules": { + "semicolon": false, + "unified-signatures": false + } +}