face-recognition.js/public_html/js/lib/image-loader.js

80 lines
2.2 KiB
JavaScript
Raw Normal View History

/* CONSTRUCTEUR
*
* @imageElement<HTMLImageElement> Image cible
* @callback<Function> Fonction à appliquer après initialisation
* @src<String> Chemin de la resource
* @process<Function> Fonction à appeller après chargement image
*
*
*/
2016-10-05 08:49:25 +00:00
var ImageLoader = function(imageElement, callback){
/* [0] Initialisation + paramètres
=========================================================*/
this._wrapper = (imageElement instanceof HTMLImageElement) ? imageElement : null;
this.src = null;
this._src = null;
this._callback = typeof callback != 'function' ? function(){} : callback;
this._process = typeof process != 'function' ? function(){} : process;
this._loaded = false;
if( !this._wrapper )
throw new Error('Param 1 expected to be an HTMLImageElement (<img>), but '+imageElement.constructor.name+' received');
/* [1] Définition du setter
=========================================================*/
this.__defineSetter__('src', function(v){
log('src update', '[ImageLoader]');
this._src = v;
this._load();
});
this.__defineGetter__('src', function(){
return this._src;
});
/* [2] Chargement de la liste d'images
=========================================================*/
AJAX.send('./pictures/index.php', (function(response){
this._images = JSON.parse(response);
this._loaded = true;
log('initialized', '[ImageLoader]');
2016-10-05 08:49:25 +00:00
this._callback.call(this);
}).bind(this), 'GET');
};
2016-10-05 08:49:25 +00:00
2016-10-05 08:49:25 +00:00
/* CHARGEMENT D'IMAGE
*
*/
ImageLoader.prototype._load = function(){
if( !this._loaded )
2016-10-05 08:49:25 +00:00
throw new Error('image tree not loaded yet');
/* [0] Initialisation des paramètres
=========================================================*/
if( typeof this.src != 'string' )
throw new Error('ImageLoader.src expected to be a <String>');
2016-10-05 08:49:25 +00:00
if( typeof this._callback != 'function' )
throw new Error('ImageLoader.callback expected to be a <Function>');
2016-10-05 08:49:25 +00:00
if( !~this._images.indexOf(this.src) ){
console.warn('Resource '+this.src+' not found!');
2016-10-05 08:49:25 +00:00
return;
}
/* [1] On charge l'image + callback
=========================================================*/
this._wrapper.addEventListener('load', this._process.bind(this._wrapper), false);
this._wrapper.src = './pictures/' + this.src;
2016-10-05 08:49:25 +00:00
return true;
};