gpt4 book ai didi

javascript - 通过一次加载绘制图像数组?

转载 作者:行者123 更新时间:2023-12-03 10:46:46 24 4
gpt4 key购买 nike

我想用一个 onload 函数绘制一行图像。我已经尝试过这段代码

for(i = 0; i < 8; i++){
var canvas = document.getElementById('ctx');
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "thumb.png";
imageObj.setAtX = i * 10;
imageObj.setAtY = i * 10;
imageObj.onload = function() {
context.drawImage(this, this.setAtX, this.setAtY);
};
}

(在java脚本中)

最佳答案

// put the paths to your images in imageURLs[]
var imageURLs=[];
imageURLs.push("image1.png");
imageURLs.push("image2.png");

// the loaded images will be placed in imgs[]
var imgs=[];

var imagesOK=0;
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[]

}

关于javascript - 通过一次加载绘制图像数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28552385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com