【问题标题】:how to add functions to CanvasRenderingContext2D prototype in typescript如何在打字稿中向 CanvasRenderingContext2D 原型添加函数
【发布时间】:2019-04-23 14:09:42
【问题描述】:

我想在 CanvasRenderingContext2D 上添加一个函数。它的作用是绘制一个圆形文本。

在 javascript 中,我需要做的就是编写如下代码:

CanvasRenderingContext2D.prototype.fillTextCircle = function () {
    //some code       
}

但是它在 typescript 中不起作用。

我也尝试了这两种方法:

1。 在文件头添加如下代码

interface CanvasRenderingContext2D {
    fillTextCircle: any;
}

CanvasRenderingContext2D.prototype.fillTextCircle = function () {
    //some code       
}

2。 在 lib.dom.d.ts 中添加这一行

interface CanvasRenderingContext2D extends CanvasState, CanvasTransform, CanvasCompositing, CanvasImageSmoothing, CanvasFillStrokeStyles, CanvasShadowStyles, CanvasFilters, CanvasRect, CanvasDrawPath, CanvasUserInterface, CanvasText, CanvasDrawImage, CanvasImageData, CanvasPathDrawingStyles, CanvasTextDrawingStyles, CanvasPath {
    readonly canvas: HTMLCanvasElement;
    fillTextCircle: any;   //add this line in lib.dom.d.ts
}

但它仍然抱怨这个错误:

类型上不存在属性“fillTextCircle” 'CanvasRenderingContext2D'。

【问题讨论】:

  • 请检查其他问题,例如here.
  • 好的,我明白了!所以我不能直接在 lib.dom.d.ts 中修改接口,但我创建了一个 global.d.ts 并添加以下代码:` interface CanvasRenderingContext2D { fillTextCircle: any; } ` 它有效!

标签: javascript typescript


【解决方案1】:

只需添加一个 global.d.ts,并添加以下代码:

 interface CanvasRenderingContext2D {
    fillTextCircle: any;
}

会有用的

link question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    相关资源
    最近更新 更多