我将多个png透明图像添加到另一个上面的html5画布中,但它们没有以正确的顺序堆叠(由包含这些图像的url的数组定义)
我在其他讨论中读到,这可能是一个封闭问题,但到目前为止还没有解决方案。
这是我的代码:
function drawCanvas() {
var canvas;
var context;
var imgArray = [
'images/img1.png',
'images/img2.png',
'images/img3.png',
'images/img4.png',
'images/img5.png',
'images/img6.png'
];
canvas = document.getElementById('myCanvas');
context = canvas.getContext("2d");
for (var i = 0; i < imgArray.length; i++) {
var img = new Image();
img.src = imgArray[i];
var drawTee = function(i, context, canvas) {
return function() {
console.log(i, 'loaded')
context.drawImage(this, 0, 0);
}
};
img.onload = drawTee(i, context, canvas);
}
};
任何人都可以帮助我吗?
答案 0 :(得分:1)
问题是画布上图像的顺序取决于图像加载的顺序。
解决方案:等待所有图像完成加载,然后将它们添加到画布
function drawCanvas() {
var canvas;
var context;
var imgArray = [
'images/img1.png',
'images/img2.png',
'images/img3.png',
'images/img4.png',
'images/img5.png',
'images/img6.png'
];
var images = [];
canvas = document.getElementById('myCanvas');
context = canvas.getContext("2d");
var loadCount = 0;
for (var i = 0; i < imgArray.length; i++) {
var img = new Image();
img.src = imgArray[i];
images.push(img);
img.onload = function() {
if(++loadCount == imgArray.length) {
for(var i=0; i < imgArray.length; i++) {
context.drawImage(images[i], 0, 0);
}
}
};
}
};