用于保持对HTML5 Canvas的Jquery引用的Typescript变量

时间:2012-12-11 12:43:07

标签: typescript

嗨我想知道我是否以正确的方式执行此操作,我希望有一个Typescript变量来保持对HTML5 Canvas的Jquery引用。我有一个无类型的canvas对象,它从$(document).ready中的行传递给构造函数。

game.ts:

///<reference path="../javascripts/sprite.js" />
///<reference path="d.ts/jquery-1.8.d.ts" />
///<reference path="../javascripts/jquery-1.8.2.js/>


        $(document).ready(function () {
        canvas = $('#canvas');

        })
    });

class Game {

    canvas;

    CANVAS_WIDTH: number;
    CANVAS_HEIGHT: number;

    constructor (canvas) {
        this.canvas = canvas;
        this.CANVAS_WIDTH = canvas.width();
        this.CANVAS_HEIGHT = canvas.height();
    }

但是在游戏类中使用这个canvas变量时,我没有像.width()那样得到任何jquery语法自动完成;

2 个答案:

答案 0 :(得分:4)

解决方案,使用JQuery变量:

class Game {

     canvas : JQuery;

    CANVAS_WIDTH: number;
    CANVAS_HEIGHT: number;

    constructor (canvas:JQuery) {
        this.canvas = canvas;

        this.CANVAS_WIDTH = canvas.width();
        this.CANVAS_HEIGHT = canvas.height();
    }

答案 1 :(得分:4)

更好的方法(使用HTMLCanvasElement类型),虽然丢失width()属性是指像这样引用Canvas。

  canvas: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById('canvas');

context2D: CanvasRenderingContext2D;