我正在尝试从URL加载多个图像,然后将它们绘制到一个画布元素中。但我不想为我必须加载的每个图像重新创建相同的代码。
loadImage函数(它工作得很好):
function loadImage(divId, imgId, path, width, height) {
var img = $("<img />").attr({ 'id': imgId, 'src': path , 'width': width, 'height': height, 'style': "display:none"})
.load(function () {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image: ' + imgId);
} else {
$("#" + divId).append(img);
}
});}
但我想多次调用loadImage,然后在画布上绘制所有图像:
function myTheme()
{
loadImage("ContentBox", "bottom", "http://mydomain/images/bottom.jpg", 400, 391);
loadImage("ContentBox", "left", "http://mydomain/images/left.jpg", 400, 391);
loadImage("ContentBox", "right", "http://mydomain/images/right.jpg", 400, 391);
loadImage("ContentBox", "top", "http://mydomain/images/top.jpg", 400, 391);
// I need to wait ALL loads before using getElementById (these lines below don't work)
_imgBottom = document.getElementById("bottom");
_imgLeft = document.getElementById("left");
_imgRight = document.getElementById("right");
_imgTop = document.getElementById("top");
Context.drawImage(_imgBottom, 0, 0);
Context.drawImage(_imgLeft, 0, 0);
Context.drawImage(_imgRight, 0, 0);
Context.drawImage(_imgTop, 0, 0);
}我该怎么做呢?
谢谢
发布于 2013-12-14 01:38:32
有许多方法可以在开始使用之前加载所有图像。
这里有一种方法:
// image loader
var imagesOK=0;
var imgs=[]; // the fully loaded Image objects will be here in the imgs[] array
var imageURLs=[]; // put the paths to your images in the imageURLs[] array
// push the image urls into an array
imageURLs.push("http://mydomain/images/bottom.jpg");
imageURLs.push("http://mydomain/images/left.jpg");
imageURLs.push("http://mydomain/images/right.jpg");
imageURLs.push("http://mydomain/images/top.jpg");
// begin loading
loadAllImages();
function loadAllImages(){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
// start() is called when all images are fully loaded
start();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// imgs[0] == bottom.jpg
// imgs[1] == left.jpg
// imgs[2] == right.jpg
// imgs[3] == top.jpg
}发布于 2013-12-16 02:25:38
如果你的目标是能够简单地加载一组图像,你可以使用像my YAIL bulk image loader这样的东西(MIT license =免费且灵活)。
只需设置加载器(这只是众多方法中的一种,请参阅上面的链接了解完整用法):
var loader = (new YAIL({
done: drawImages,
urls: [
"http://mydomain/images/bottom.jpg",
"http://mydomain/images/left.jpg",
"http://mydomain/images/right.jpg",
"http://mydomain/images/top.jpg"
]
})).load();然后,当加载完所有图像后,您只需迭代图像数组,该数组的顺序与url列表相同:
function drawImages(e) {
for(var i = 0, img; img = e.images[i]; i++)
context.drawImage(img, 0, 0);
}理想情况下,您应该提供一个错误处理程序(此处未显示),还可以选择提供进度处理程序。
如果你为了教育目的而尝试这样做,那么请看一下它的源代码。
https://stackoverflow.com/questions/20570944
复制相似问题