[英]Drawing array of images on CANVAS
我正在嘗試在畫布上繪制圖像數組,但是onload方法存在問題。
我認為這可能是一個問題,因為無法在onload完成之前將圖像繪制在畫布上,並且因為它在FOR內可能丟失了所有引用...
這是我的代碼:
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Create an image element
var bg = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
ctx.drawImage(bg, 0, 0);
}
// Specify the src to load the image
fondo.src = "../img/auxfinal.png";
img.src = "../img/bolso.png";
// var res is is my array where i have on each position (img name, x, y)
var arrayLength = res.length;
for (var i = 0; i < arrayLength; i++) {
var aux = document.createElement('IMG');
aux.onload = function () {
ctx.drawImage(aux, res2[1].substr(0,res2[1].length-2), res2[2].substr(0,res2[2].length-2));
}
}
正如@gtramontina所說,您的aux加載循環將不起作用,因為它沒有設置任何.src,而且還因為第一個aux變量將被循環中的第二次傳遞殺死(等)。
您可能想在工具箱中添加一個圖像加載器...這里是一個(但有很多):
// image loader
var imagesOK=0;
var imgs=[];
var imageURLs=[];
// put the paths to your images here
imageURLs.push("../img/auxfinal.png");
imageURLs.push("../img/bolso.png");
// ... and push all your other images also
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// for example,
// auxfinal.png is in imgs[0] & this will draw auxfinal.png
ctx.drawImage(imgs[0],0,0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.