Question

This code loads images for a javascript application:

var sampleImage = new Image();
sampleImage.ready = false;
sampleImage.onload = setAssetReady;
sampleImage.src = IMAGE_FILE;

function setAssetReady(){
this.ready = true;
}

I'd like to figure out a way to not use four lines of code for every image being used.

I used this way suggested by the answer (Unless I'm doing it wrong):

var sampleImage = new Image();
sampleImage = loadTheImage(imageFile);

function loadTheImage(imageFile){
this.ready = false;
this.onload = setAssetReady;
this.src = imageFile;
}

function setAssetReady(){
this.ready = true;
}

The images did not load successfully and when sampleImage.ready was evaluated in an if statement in a different place in the code, an error message was returned that said:

Cannot read property 'ready' of undefined

And again, I'm doing this process for many images, so I only want one or two lines of code to write for each instead of the four I originally had. Or if there is any other process you suggest.

Was it helpful?

Solution

function loadTheImage(imageFile){
    sampleImage.ready = false;
    sampleImage.onload = setAssetReady;
    sampleImage.src = imageFile;
};
function setAssetReady(){
    this.ready = true;
};

And then just call loadTheImage for every image.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top