TypeScriptを使用してクラスコンストラクタを使用してHTML5キャンバスに子猫を描画しようとしていますが、このタスクを達成する方法がわかりません。私は実際に何が起きているのか予想される振る舞いに基づいて何をしようとしているのかを示すコードをコメントしました。タイマーやアドバイスをありがとうございます。あなたのコードからTypeScriptクラス.drawImage
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.
*/
}
}
}
新しいImage()を宣言してsrcを設定しているので、あなたのdrawImageの呼び出しは間違いなくsrcがロードされる前になります。 DOMから)新しい画像と負荷を作成する必要はありません –
@AMacdonaldあなたの説明をお寄せいただきありがとうございます!私は今よく理解する。私はこのクラスの外に画像をロードすべきですか? this.context.drawImage()を使用する前にクラスのメソッドを使用してイメージをロードしようとしたとき、それは機能しませんでした。私はOOPデザインに固執しようとしています:)私はキャンバスに4匹の子猫を描く必要があります。私はそれをロードして配列に格納するほうが良いと思っていますが、その配列をどこに作成するかはわかりません。他の洞察をありがとうございます:) – decahub
srcを設定すると負荷がトリガーされます - 別のクラスでやっても、待ち時間が長くなり、確実にできません - あなたがローダーの場合は、あなたが使用している画像の中で唯一の方法は、画像が既にDOMに読み込まれている場合です。あなたが見たキャンバスの例が、関係する画像の読み込みを開始するように設計されていることがわかります –