我制作了这个加载器,它允许您向其中添加所有图像 URL,然后调用load()
以启动加载。
您可以使用这种加载器来支持进度回调,以便向用户显示当前进度。
如果您需要跨域图像,您可以通过添加一个标志来添加对此的支持,以告诉加载的图像为您设置 crossOrigin 类型。以下示例为所有图像设置了此项,但可以对其进行扩展以支持单个图像。
现场演示在这里
装载机:
/// callback - function to call when finished (mandatory)
/// progress - function to call for each image loaded (optional)
/// progress contains an argument with an "event" containing properties
/// img (the image loaded), url, current (integer) and total (integer)
function imageLoader(callback, progress, error) {
if (typeof callback !== 'function') throw 'Need a function for callback!';
var lst = [],
crossOrigin = false;
this.crossOrigin = function (state) {
if (typeof state !== 'bool') return crossOrigin;
crossOrigin = state;
return this;
}
this.add = function (url) {
lst.push(url);
return this;
}
this.load = function () {
if (lst.length > 0) {
startLoading();
}
return this;
}
function startLoading() {
var i = 0,
url,
count = lst.length,
images = [];
for (; url = lst[i]; i++) {
var img = document.createElement('img');
images.push(img);
img.onload = function () {
_handler(url, this)
};
img.onerror = function (e) {
_handlerError(url, e)
};
if (crossOrigin === true) img.crossOrigin = 'anonymous';
img.src = url;
}
function _handler(url, img) {
count--;
if (typeof progress === 'function') progress({
current: lst.length - count,
total: lst.length,
url: url,
img: img
});
if (count === 0) callback({
images: images,
urls: lst
});
}
function _handlerError(url, e) {
if (typeof error === 'function') error({
url: url,
error: e
});
console.warn('WARNING: Could not load image:', url);
_handler();
}
}
return this;
}
用法:
var loader = new imageLoader(done, progress);
/// methods can be chained:
loader.add(url1)
.add(url2)
.add(url3)
.load();
(完整示例请参见演示)
然后处理程序可以执行以下操作:
function done(e) {
for (i = 0; i < e.images.length; i++) {
/// draw the image
ctx.drawImage(e.images[i], i * 20, i * 20, 40, 40);
}
}
function progress(e) {
///progress bar
status.style.width = ((e.current / e.total) * 100).toFixed(0) + '%';
/// current loaded image
ctx.drawImage(e.img, 0, 340, 60, 60);
}