HTML5 canvas how to draw one picture on top of another

canvas, html, javascript

Solution

Store your images in an array instead. That will makes sure the order is kept no matter which image finish loading first:

var ctx = document.getElementById("main").getContext("2d");
var background = new Image();
var photo = new Image();
var images = [background, photo]; /// the key
var count = images.length;

background.onload = photo.onload = counter;
background.src = "background.jpg";
photo.src = "photo.jpg"

/// common loader keeping track if loads
function counter() {
    count--;
    if (count === 0) drawImages();
}

/// is called when all images are loaded
function drawImages() {
    for(i = 0; i < images.length; i++)
        ctx.drawImage(images[i], 0, 0);
}

(the draw method assumes all being drawn at position 0,0 - of course, change this to meet your criteria).

Problem

I want to draw two images on the same canvas. The first image is background.jpg and the second is photo.jpg. I want the photo.jpg always on top of the other: ``` var ctx = document.getElementById("main").getContext("2d"); var background = new Image(); var photo = new Image(); background.onload = function() { ctx.drawImage(background, 0, 0); } photo.onload = function() { ctx.drawImage(photo, 0, 0); } background.src = "background.jpg"; photo.src = "photo.jpg" ``` My question is how can I make sure the photo is always on the top. Because the onload are callbacks, I cannot make any assumptions about the calling order. Thanks!

Original source