image.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import LRU from '../../core/LRU.js';
  2. import { platformApi } from '../../core/platform.js';
  3. var globalImageCache = new LRU(50);
  4. export function findExistImage(newImageOrSrc) {
  5. if (typeof newImageOrSrc === 'string') {
  6. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  7. return cachedImgObj && cachedImgObj.image;
  8. }
  9. else {
  10. return newImageOrSrc;
  11. }
  12. }
  13. export function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  14. if (!newImageOrSrc) {
  15. return image;
  16. }
  17. else if (typeof newImageOrSrc === 'string') {
  18. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  19. return image;
  20. }
  21. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  22. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  23. if (cachedImgObj) {
  24. image = cachedImgObj.image;
  25. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  26. }
  27. else {
  28. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  29. image.__zrImageSrc = newImageOrSrc;
  30. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  31. image: image,
  32. pending: [pendingWrap]
  33. });
  34. }
  35. return image;
  36. }
  37. else {
  38. return newImageOrSrc;
  39. }
  40. }
  41. function imageOnLoad() {
  42. var cachedImgObj = this.__cachedImgObj;
  43. this.onload = this.onerror = this.__cachedImgObj = null;
  44. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  45. var pendingWrap = cachedImgObj.pending[i];
  46. var cb = pendingWrap.cb;
  47. cb && cb(this, pendingWrap.cbPayload);
  48. pendingWrap.hostEl.dirty();
  49. }
  50. cachedImgObj.pending.length = 0;
  51. }
  52. export function isImageReady(image) {
  53. return image && image.width && image.height;
  54. }