whitebear
whitebear

Reputation: 12445

how to make assure the load order of images on canvas

I have two images to draw on canvas.

I would like to make sure A is shown on B.

var Apic = new Image();
var Bpic = new Image();

Apic.src = "Apic.png";
Bpic.src = "Bpic.png";

// I want to add z-index to 

Apic.style  =  "z-index:1;";
Bpic.style  =  "z-index:2;";

Apic.onload = function() {
    context.drawImage(Apic 0,0);
};

Bpic.onload = function() {
    context.drawImage(Bpic,0,0);
};

However,it doesn't work ,any good solution??


I have soloved the problem like this with Ken Fyrstenberg help.

Bpic is drawn on Apic every time.

It might not the good way though, it can solve the problem for now.

Apic.onload = function() {
    context.drawImage(Apic 0,0);
    context.drawImage(Bpic,0,0);
};

Bpic.onload = function() {
    context.drawImage(Bpic,0,0);
};

Upvotes: 0

Views: 173

Answers (1)

user1693593
user1693593

Reputation:

Just put urls into an array. Create image elements in the same order to a parallel array. This will keep the order tight. Then you need to count the successful loads so we are sure we have all image data that is needed:

var urls = ["Apic.png", "Bpic.png"];      // url and order
var pics = [];                            // holds the image elements                 
var count = urls.length;                  // number of images to load

for(var i = 0, url; url = urls[i++];) {   // share onload handler
    var pic = new Image();                // create a new image
    pics.push(pic);                       // store in array
    pic.onload = loadCounter;             // set load handler (also add for error)
    pic.src = url;                        // set url to start loading
}

function loadCounter() {
    count--;
    if (!count) {                         // when done we can draw the images in order:
        for(var i = 0, pic; pic = pics[i++];) {
            context.drawImage(pic, 0, 0);
        }
    }
};

Upvotes: 1

Related Questions