我正在创建一个示例程序,用于在画布上显示图像,但希望将实际绘图过程包含在自定义对象中。
以下代码不会显示图像,因为 pictFrame.img.onload 无法捕获图像文件的onload事件。 Chrome控制台说“TypeError:无法使用表达式设置属性'onload'未定义”,尽管它可以正确评估 pictFrame.img.src 或 pictFrame.img.height 。 / p>
如何检测创建对象时正在启动的图像加载?
<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>
答案 0 :(得分:1)
因为你在pictFrame实例化之前调用它。你在chrome中得到这个,
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
而不是之前调用它。