0

キャンバスに画像を表示するサンプルプログラムを作成していますが、実際の描画処理をカスタムオブジェクトに囲みたいと思っています。

次のコードは、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>
4

1 に答える 1

1

pictFrame がインスタンス化される前に呼び出しているためです。あなたはクロムでこれを手に入れます、

Uncaught TypeError: Cannot set property 'onload' of undefined 

代わりに以下のようにしてください。

window.onload = function()
{
    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");
    pictFrame = new pictFrame(context, "images/bahu.png", 10, 10, 200, 200);
    console.log("called");
    pictFrame.img.onload = function()      
    {
        console.log(" onload called");
        pictFrame.draw();
    }
};

つまり、前に呼び出すのではなく、終了 onload後に呼び出してください。window.onload

于 2013-06-15T06:31:42.270 に答える