我正在创建一个示例程序以在画布上显示图像,但希望将实际绘图过程包含在自定义对象中。
以下代码不会显示图像,因为pictFrame.img.onload无法捕获图像文件的 onload 事件。尽管 Chrome 控制台可以正确评估pictFrame.img.src或pictFrame.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>