キャンバスに画像を表示するサンプルプログラムを作成していますが、実際の描画処理をカスタムオブジェクトに囲みたいと思っています。
次のコードは、pictFrame.img.onloadが画像ファイルの onload イベントをキャッチできないため、画像を表示しません。Chrome コンソールは、 pictFrame.img.srcまたはpictFrame.img.heightを正しく評価できますが、「TypeError: Cannot set property 'onload' of undefined」という式を表示します。
オブジェクトの作成時に開始されるイメージの読み込みを検出するにはどうすればよいですか?
<html>
<head>
<script type="text/javascript">
function pictFrame(context, imgsrc, pos_x, pos_y, size_x, size_y)
{
this.context = context;
this.img = new Image();
this.img.src = imgsrc;
this.pos_x = pos_x;
this.pos_y = pos_y;
this.size_x = size_x;
this.size_y = size_y;
this.draw = function() {
this.context.drawImage(this.img, this.pos_x, this.pos_y, this.size_x, this.size_y);
};
}
// These variables must live while the page is being displayed.
// Therefore, they can't be defined within window.onload function.
var canvas;
var context;
var pictFrame;
window.onload = function()
{
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
pictFrame = new pictFrame(context, "darwin.jpg", 10, 10, 200, 200);
};
pictFrame.img.onload = function() // Can't catch onload event
{
pictFrame.draw();
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="300"></canvas>
</body>
</html>