TypeScript类.drawImage

时间:2016-05-30 19:50:20

标签: javascript html5 typescript

我正在尝试使用TypeScript通过类构造函数在HTML5画布中绘制一只小猫,但我对如何实现该任务感到困惑。我已根据我预期的行为与实际工作的内容对代码进行了评论,以显示我尝试做的事情。非常感谢您的计时器和建议。

module Game {

    export class Test {

        width: number;
        height: number;

        cellWidth: number;
        cellHeight: number;

        canvas: HTMLCanvasElement;
        context: CanvasRenderingContext2D;

        constructor() {

            this.width = 28;
            this.height = 31;

            this.cellWidth = 20;
            this.cellHeight = 20;

            this.canvas = <HTMLCanvasElement> document.getElementById("game_canvas");
            this.context = this.canvas.getContext("2d");
            this.canvas.width = this.width * this.cellWidth;
            this.canvas.height = this.height * this.cellHeight;

            this.context.fillStyle = "blue";
            this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);

            let kitten = new Image();
            kitten.src = 'img/kitten.png';

            // When trying to draw a kitten in the canvas,
            // this will work:

            kitten.onload = () => {
                this.context.drawImage(kitten, 0, 0);
            };

            // but this work won't:
            //this.context.drawImage(kitten, 0, 0);

            /*
            I was assuming that by accessing the this.context property
            I would have direct access to the canvas and I will be able to use
            drawImage to draw the kitten on it; however, that approach
            produces no kitten in the canvas.
            Only by using the .onload method it works.
            I am using the () => notation so that the this inside the block
            is referring to the class.
            I have seen many JavasScript files in which images are simple drawn
            through:
            context.drawImage(image, 0, 0);
            They are not embedded in .onload
            I have tried to Google information but I cannot pinpoint what is
            happening.
             */
        }
    }
}

2 个答案:

答案 0 :(得分:1)

从你的代码:

        let kitten = new Image();
        kitten.src = 'img/kitten.png';

        // When trying to draw a kitten in the canvas,
        // this will work:

        kitten.onload = () => {
            this.context.drawImage(kitten, 0, 0);
        };

        // but this work won't:
        //this.context.drawImage(kitten, 0, 0);

使用onload是您获得可在画布上绘制的图像的实际方法。微优化将保留已加载图像的字典,以便在绘制多个小猫时可以重复使用它们。

答案 1 :(得分:1)

根据我的评论,这里是我的答案:很简单,因为你宣布一个新的Image()并设置src,你的drawImage调用无疑会在src被加载之前...如果你要使用先前加载的图像(例如来自DOM)然后不需要创建新图像和加载

设置src会触发加载 - 在另一个类中执行此操作仍会使您等待加载的等待时间,而您无法确定 - 我会说使用onload是防弹且必不可少的,如果您是正在使用的图像的加载器 - 唯一的替代方法是当图像已经加载到DOM中(或预先加载到其他地方)时,您可能会发现您看到的画布示例旨在启动有关图像的加载