ImageLoader.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. import { Cache } from './Cache.js';
  5. import { DefaultLoadingManager } from './LoadingManager.js';
  6. function ImageLoader( manager ) {
  7. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  8. }
  9. Object.assign( ImageLoader.prototype, {
  10. crossOrigin: 'anonymous',
  11. load: function ( url, onLoad, onProgress, onError ) {
  12. if ( url === undefined ) url = '';
  13. if ( this.path !== undefined ) url = this.path + url;
  14. url = this.manager.resolveURL( url );
  15. var scope = this;
  16. var cached = Cache.get( url );
  17. if ( cached !== undefined ) {
  18. scope.manager.itemStart( url );
  19. setTimeout( function () {
  20. if ( onLoad ) onLoad( cached );
  21. scope.manager.itemEnd( url );
  22. }, 0 );
  23. return cached;
  24. }
  25. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  26. function onImageLoad() {
  27. image.removeEventListener( 'load', onImageLoad, false );
  28. image.removeEventListener( 'error', onImageError, false );
  29. Cache.add( url, this );
  30. if ( onLoad ) onLoad( this );
  31. scope.manager.itemEnd( url );
  32. }
  33. function onImageError( event ) {
  34. image.removeEventListener( 'load', onImageLoad, false );
  35. image.removeEventListener( 'error', onImageError, false );
  36. if ( onError ) onError( event );
  37. scope.manager.itemError( url );
  38. scope.manager.itemEnd( url );
  39. }
  40. image.addEventListener( 'load', onImageLoad, false );
  41. image.addEventListener( 'error', onImageError, false );
  42. if ( url.substr( 0, 5 ) !== 'data:' ) {
  43. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  44. }
  45. scope.manager.itemStart( url );
  46. image.src = url;
  47. return image;
  48. },
  49. setCrossOrigin: function ( value ) {
  50. this.crossOrigin = value;
  51. return this;
  52. },
  53. setPath: function ( value ) {
  54. this.path = value;
  55. return this;
  56. }
  57. } );
  58. export { ImageLoader };