72 lines
1.6 KiB
JavaScript
72 lines
1.6 KiB
JavaScript
|
/**
|
||
|
* The image factory takes care that we only make requests for Image URLs which we have not already started downloading
|
||
|
* @param graphics GameLib.D3.Graphics
|
||
|
* @param baseUrl
|
||
|
* @returns {Function}
|
||
|
* @constructor
|
||
|
*/
|
||
|
GameLib.D3.ImageFactory = function (
|
||
|
graphics,
|
||
|
baseUrl
|
||
|
) {
|
||
|
|
||
|
graphics.isNotThreeThrow();
|
||
|
|
||
|
var promiseList = {};
|
||
|
|
||
|
return function(imagePath, progressCallback) {
|
||
|
|
||
|
if (!imagePath) {
|
||
|
console.log('Attempted to download bad URL : ' + imagePath);
|
||
|
throw new Error('Bad URL : ' + imagePath);
|
||
|
}
|
||
|
|
||
|
if (promiseList[imagePath]) {
|
||
|
return promiseList[imagePath];
|
||
|
}
|
||
|
|
||
|
var defer = Q.defer();
|
||
|
|
||
|
promiseList[imagePath] = defer.promise;
|
||
|
|
||
|
GameLib.D3.ImageFactory.LoadImage(graphics, baseUrl + imagePath, defer, progressCallback);
|
||
|
|
||
|
return promiseList[imagePath];
|
||
|
}
|
||
|
};
|
||
|
|
||
|
/**
|
||
|
* Loads an image and resolves the defered promise once it succeeded (or failed)
|
||
|
* @param graphics
|
||
|
* @param url
|
||
|
* @param defer
|
||
|
* @param progressCallback
|
||
|
* @constructor
|
||
|
*/
|
||
|
GameLib.D3.ImageFactory.LoadImage = function (
|
||
|
graphics,
|
||
|
url,
|
||
|
defer,
|
||
|
progressCallback
|
||
|
) {
|
||
|
|
||
|
var loader = new graphics.instance.ImageLoader();
|
||
|
|
||
|
loader.crossOrigin = '';
|
||
|
|
||
|
loader.load(
|
||
|
url + '?ts=' + Date.now(),
|
||
|
function (image) {
|
||
|
defer.resolve(image);
|
||
|
},
|
||
|
function onProgress(xhr) {
|
||
|
if (progressCallback) {
|
||
|
progressCallback((xhr.loaded / xhr.total * 100));
|
||
|
}
|
||
|
},
|
||
|
function onError() {
|
||
|
defer.reject('Failed to download image : ' + url);
|
||
|
}
|
||
|
);
|
||
|
};
|