为什么找不到画布(Typesrcipt)

时间:2019-07-03 22:33:40

标签: typescript canvas typeerror addeventlistener

我尝试将eventListener添加到画布。但是用代码我得到了这个错误:

$ jq '.example.new={newfield: {key: "value"}}' foobarbaz.json
{
  "example": {
    "name": "stackOverflowQuestion",
    "new": {
      "newfield": {
        "key": "value"
      }
    }
  }
}

这是打字稿

TS2339: Property 'cvs' does not exist on type 'cvsClick'.

这是HTML:

cvs:HTMLCanvasElement;
ctx:CanvasRenderingContext2D;

class cvsClick {

    constructor() {
        let cvs = <HTMLCanvasElement>document.getElementById("background");
        let ctx = cvs.getContext("2d");

        this.cvs = cvs;
        this.ctx = ctx;

        this.cvs.addEventListener('click', console.log("canvas clicked"));
    }

}
new cvsClick();

也许我的EventListener也不正确。

2 个答案:

答案 0 :(得分:0)

几乎在类的主体内声明了这些东西。

class cvsClick {
    cvs:HTMLCanvasElement;
    ctx:CanvasRenderingContext2D | null;
    constructor() {
        let cvs = <HTMLCanvasElement>document.getElementById("background");
        let ctx = cvs.getContext("2d");

        this.cvs = cvs;
        this.ctx = ctx;

        this.cvs.addEventListener('click', console.log("canvas clicked"));
    }

}
new cvsClick();

答案 1 :(得分:0)

感谢您的回答,它有效。错误消失了。仍然我必须将事件监听器更改为

        this.cvs.addEventListener('click', () => {
            console.log("canvas clicked");
        });