RaptorDotCpp
RaptorDotCpp

Reputation: 1465

JavaScript Image onload not called

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.

Upvotes: 3

Views: 9954

Answers (2)

you may think that it's a hard way but believe me it's not: if you want to use jQuery load Event for images let me tell you a truth : "That Is a SHIT" so you should use :

.imagesLoaded()

but before using that you should first download it here after downloading do these steps:

  1. attach your .imagesLoaded() library js file into your first code as you did for main jQuery.js
  2. write this code for the image you want to check if loaded or not:

    $('#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. put the address of you picture instead of #container in the code ENJOY:))

Upvotes: 1

Dmitry
Dmitry

Reputation: 99

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.

Upvotes: 2

Related Questions