1 | ;
|
2 |
|
3 | /**
|
4 | * Loads {@link external:image}s and lets you know when they're all available. An instance of ImageLoader is available as {@link Splat.Game#images}.
|
5 | * @constructor
|
6 | */
|
7 | function ImageLoader(onLoad) {
|
8 | /**
|
9 | * The key-value object that stores named {@link external:image}s
|
10 | * @member {object}
|
11 | * @private
|
12 | */
|
13 | this.images = {};
|
14 | /**
|
15 | * The total number of images to be loaded.
|
16 | * @member {number}
|
17 | * @private
|
18 | */
|
19 | this.totalImages = 0;
|
20 | /**
|
21 | * The number of images that have loaded completely.
|
22 | * @member {number}
|
23 | * @private
|
24 | */
|
25 | this.loadedImages = 0;
|
26 | /**
|
27 | * The names of all the images that were requested to be loaded.
|
28 | * @member {Array}
|
29 | * @private
|
30 | */
|
31 | this.names = [];
|
32 | /**
|
33 | * A callback to be called once all images are loaded.
|
34 | * @member {Array}
|
35 | * @private
|
36 | */
|
37 | this.onLoad = onLoad;
|
38 | }
|
39 | /**
|
40 | * Load an {@link external:image}.
|
41 | * @param {string} name The name you want to use when you {@link ImageLoader#get} the {@link external:image}
|
42 | * @param {string} path The path of the {@link external:image}.
|
43 | */
|
44 | ImageLoader.prototype.load = function(name, path) {
|
45 | // only load an image once
|
46 | if (this.names.indexOf(name) > -1) {
|
47 | return;
|
48 | }
|
49 | this.names.push(name);
|
50 |
|
51 | this.totalImages++;
|
52 |
|
53 | var img = new Image();
|
54 | var self = this;
|
55 | img.addEventListener("load", function() {
|
56 | self.loadedImages++;
|
57 | self.images[name] = img;
|
58 | if (self.allLoaded() && self.onLoad) {
|
59 | self.onLoad();
|
60 | }
|
61 | });
|
62 | img.addEventListener("error", function() {
|
63 | console.error("Error loading image " + path);
|
64 | });
|
65 | img.src = path;
|
66 | };
|
67 | ImageLoader.prototype.loadFromManifest = function(manifest) {
|
68 | var keys = Object.keys(manifest);
|
69 | var self = this;
|
70 | keys.forEach(function(key) {
|
71 | self.load(key, manifest[key]);
|
72 | });
|
73 | };
|
74 |
|
75 | /**
|
76 | * Test if all {@link external:image}s have loaded.
|
77 | * @returns {boolean}
|
78 | */
|
79 | ImageLoader.prototype.allLoaded = function() {
|
80 | return this.totalImages === this.loadedImages;
|
81 | };
|
82 | /**
|
83 | * Retrieve a loaded {@link external:image}.
|
84 | * @param {string} name The name given to the image during {@link ImageLoader#load}.
|
85 | * @returns {external:image}
|
86 | */
|
87 | ImageLoader.prototype.get = function(name) {
|
88 | return this.images[name];
|
89 | };
|
90 |
|
91 | module.exports = ImageLoader;
|