0

我正在创建一个示例程序以在画布上显示图像,但希望将实际绘图过程包含在自定义对象中。

以下代码不会显示图像,因为pictFrame.img.onload无法捕获图像文件的 onload 事件。尽管 Chrome 控制台可以正确评估pictFrame.img.srcpictFrame.img.height,但 Chrome 控制台会显示“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();
    }
};

我的意思是,在完成onloadwindow.onload调用而不是之前调用它。

于 2013-06-15T06:31:42.270 回答