admin管理员组

文章数量:1303066

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!

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!

Share Improve this question edited Dec 1, 2013 at 20:56 CraigTeegarden 8,2518 gold badges39 silver badges43 bronze badges asked Dec 1, 2013 at 20:51 darklorddarklord 5,16714 gold badges43 silver badges70 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

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"

/// mon 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).

The foreground could be loaded in the callback for the background

var ctx = document.getElementById("main").getContext("2d");
var background = new Image();
var photo = new Image();

background.onload = function() {    
  ctx.drawImage(background, 0, 0);
  photo.src = "photo.jpg" // after background is loaded, load foreground
}

photo.onload = function() {
  ctx.drawImage(photo, 0, 0);  
}

background.src = "background.jpg";

本文标签: javascriptHTML5 canvas how to draw one picture on top of anotherStack Overflow