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() {
|
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 | /**
|
34 | * Load an {@link external:image}.
|
35 | * @param {string} name The name you want to use when you {@link ImageLoader#get} the {@link external:image}
|
36 | * @param {string} path The path of the {@link external:image}.
|
37 | */
|
38 | ImageLoader.prototype.load = function(name, path) {
|
39 | // only load an image once
|
40 | if (this.names.indexOf(name) > -1) {
|
41 | return;
|
42 | }
|
43 | this.names.push(name);
|
44 |
|
45 | this.totalImages++;
|
46 |
|
47 | var img = new Image();
|
48 | var self = this;
|
49 | img.addEventListener("load", function() {
|
50 | self.loadedImages++;
|
51 | self.images[name] = img;
|
52 | });
|
53 | img.addEventListener("error", function() {
|
54 | console.error("Error loading image " + path);
|
55 | });
|
56 | img.src = path;
|
57 | };
|
58 | /**
|
59 | * Test if all {@link external:image}s have loaded.
|
60 | * @returns {boolean}
|
61 | */
|
62 | ImageLoader.prototype.allLoaded = function() {
|
63 | return this.totalImages === this.loadedImages;
|
64 | };
|
65 | /**
|
66 | * Retrieve a loaded {@link external:image}.
|
67 | * @param {string} name The name given to the image during {@link ImageLoader#load}.
|
68 | * @returns {external:image}
|
69 | */
|
70 | ImageLoader.prototype.get = function(name) {
|
71 | var img = this.images[name];
|
72 | if (img === undefined) {
|
73 | console.error("Unknown image: " + name);
|
74 | }
|
75 | return img;
|
76 | };
|
77 |
|
78 | module.exports = ImageLoader;
|