HTML5画布如何在另一个上面绘制一张图片

时间:2013-12-01 20:51:53

标签: javascript html5 canvas

我想在同一个画布上绘制两个图像。第一张图片是background.jpg,第二张图片是photo.jpg。我希望photo.jpg永远在另一个之上:

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"

我的问题是如何确保照片始终位于顶部。因为onload是回调,所以我不能对调用顺序做任何假设。谢谢!

2 个答案:

答案 0 :(得分:3)

将图像存储在数组中。这将确保无论首先加载哪个图像完成,都会保留订单:

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);
}

(绘制方法假设所有被绘制在位置0,0 - 当然,改变它以符合您的标准)。

答案 1 :(得分:1)

前景可以加载到背景的回调中

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";