3

I'm trying to draw an image on the Canvas in Javascript, but ofcourse I want to wait until the image is loaded. However, my onload function seems to be never called.

Here is what I've tried:

function GameObject(x, y)
{
    this.x = x;
    this.y = y;
    this.image = {};
    this.loaded = false;

    this.load = function(filename)
    {
        this.image = new Image();
        this.image.onload = function()
        {
            alert("image loaded");
            this.loaded = true;
        };
        this.image.src = filename;
    };
};

I'm calling the load function like this:

$( document ).ready(function()
{
    main();
});

var player = new Player(0, 0);

function main()
{
    player.load("images/player.png");
};

and Player inherits from GameObject.

When using FireBug, it looks like the image is loaded, however the alert "image loaded" is never shown and this.loaded remains false.

What could be wrong?

EDIT: The image is now loaded (there was an error in the path name), but this.loaded is never set to true, while the alert is called.

4

2 回答 2

2

You should look for loaded field in player.image object.

In order to loaded be assigned to the player object you should rewrite part of your code like this:

this.load = function(filename)
{
    var self = this;
    this.image = new Image();
    this.image.onload = function()
    {
        alert("image loaded");
        self.loaded = true;
    };
    this.image.src = filename;
};

The problem is that when onload is called the context (to what this points) is the image object. So you have to save your initial context in the self.

于 2013-06-14T13:23:17.307 回答
1

你可能认为这是一个艰难的方法,但相信我不是这样:如果你想对图像使用 jQuery 加载事件,让我告诉你一个真相:“那是​​个屁”,所以你应该使用:

.imagesLoaded()

但在使用之前,您应该先在此处 下载,下载后执行以下步骤:

  1. 将您的 .imagesLoaded() 库 js 文件附加到您的第一个代码中,就像您对主 jQuery.js 所做的那样
  2. 为要检查是否已加载的图像编写此代码:

    $('#container').imagesLoaded()
    .always( function( instance ) {
     console.log('all images loaded');
    })
    .done( function( instance ) {
    console.log('all images successfully loaded');
    })
    .fail( function() {
    console.log('all images loaded, at least one is broken');
    })
    .progress( function( instance, image ) {
    var result = image.isLoaded ? 'loaded' : 'broken';
    console.log( 'image is ' + result + ' for ' + image.img.src );
    });
    
  3. 将您的图片地址而不是#container 放在代码中 ENJOY :))

于 2018-02-07T19:16:12.243 回答