如何为模块

时间:2016-10-02 15:03:41

标签: javascript node.js canvas typescript

我想为此模块编写一个Typescript定义文件(.d.ts)https://www.npmjs.com/package/canvas

所以这就是我的开始:

declare module Canvas {
    class Canvas {
        constructor(width: number, height: number);
    }
}

declare module "canvas" {
    export = Canvas;
} 

当我导入&像这样调用模块:

/// <reference path="./canvas.d.ts" />
import * as Canvas from "canvas";
new Canvas.Canvas(32, 32)

但是,我想像这样打电话给这个班:

new Canvas(32, 32)

我还想在课堂上添加两件事:

  • 它应该返回HTMLCanvasElement所以它可以像普通的Canvas api一样工作
  • 我还想在模块中添加.Image属性,无需构造类即可访问该模块。

以下是我正在等待的一个例子:

import * as Canvas from "canvas";
var Image  = Canvas.Image;
var canvas = new Canvas(32, 32);
var ctx    = canvas.getContext('2d');

ctx.drawImage and every regular functions...
[...]

我还想向canvas.toDataURL()添加一个可选的回调参数。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这样的东西可用于实例化类,而不必在每次使用new时指定模块名称:

/// <reference path="./canvas.d.ts" />
import Canvas1 = Canvas.Canvas;

var canvas = new Canvas1(32, 32);