-
Notifications
You must be signed in to change notification settings - Fork 3
/
modules-loaders-ImageLoader.js
83 lines (72 loc) · 1.87 KB
/
modules-loaders-ImageLoader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* window.force.modules.loaders.ImageLoader
*/
/**
* TODO:
* option to create canvas instead of Images
* option to load multithread
* manage loading errors
* if we are in Cocoonjs launch an alert if the image size is not a power of 2
*/
/**
* example:
* var loader = new force.modules.loaders.ImageLoader();
* var textures = {bg1: 'assets/image1.png', bg2: 'assets/image2.png'};
* loader.setImages(textures);
* loader.setStepCb(function (c, t) { console.log(c + '/' + t); });
* loader.setFinalCb(function () { console.log('loading finished'); });
* loader.start();
* document.body.appendChild(textures.bg1);
*/
(function() {
var ImageLoader = function () {
var imgList = null;
var imgListKeys = null;
var isLoading = false;
var stepCb = null;
var finalCb = null;
var loaded = 0;
var currentPath = null;
this.setStepCb = function (cb) {
if (typeof cb == 'function') {
stepCb = cb;
}
};
this.setFinalCb = function (cb) {
if (typeof cb == 'function') {
finalCb = cb;
}
};
this.setImages = function (obj) {
imgList = obj;
};
this.debug = function() {
return imgList;
};
this.start = function () {
imgListKeys = Object.keys(imgList);
loadNext();
};
function onLoad() {
loaded++;
if (stepCb) {
stepCb(loaded, imgListKeys.length);
}
if (loaded === imgListKeys.length) {
if (finalCb) {
finalCb();
}
} else {
setTimeout(loadNext, 0);
}
};
var loadNext = function() {
currentPath = imgList[imgListKeys[loaded]];
imgList[imgListKeys[loaded]] = new Image();
imgList[imgListKeys[loaded]].onload = onLoad;
imgList[imgListKeys[loaded]].src = currentPath;
}
};
// expose module
window.force.expose('window.force.modules.loaders.ImageLoader', ImageLoader);
})();