Reputation: 11
I am creating a sample program to display an image on canvas but would like to enclose actual drawing process into a custom object.
The following code won't show the image as pictFrame.img.onload
can't catch onload
event of image file. Chrome console says "TypeError: Cannot set property 'onload' of undefined" with the expression although it can correctly evaluate pictFrame.img.src
or pictFrame.img.height
.
How should I detect image loading which is being initiated when the object is created?
<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>
Upvotes: 0
Views: 509
Reputation: 6881
Its because you are calling before pictFrame gets instantiated. You get this in chrome,
Uncaught TypeError: Cannot set property 'onload' of undefined
do like below instead,
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();
}
};
I mean, do onload
call after window.onload
has finished instead of calling it before.
Upvotes: 1