image.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import LRU from '../../core/LRU';
  2. var globalImageCache = new LRU(50);
  3. export function findExistImage(newImageOrSrc) {
  4. if (typeof newImageOrSrc === 'string') {
  5. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6. return cachedImgObj && cachedImgObj.image;
  7. }
  8. else {
  9. return newImageOrSrc;
  10. }
  11. }
  12. export function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  13. if (!newImageOrSrc) {
  14. return image;
  15. }
  16. else if (typeof newImageOrSrc === 'string') {
  17. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  18. return image;
  19. }
  20. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  21. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  22. if (cachedImgObj) {
  23. image = cachedImgObj.image;
  24. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  25. }
  26. else {
  27. image = new Image();
  28. image.onload = image.onerror = imageOnLoad;
  29. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  30. image: image,
  31. pending: [pendingWrap]
  32. });
  33. image.src = image.__zrImageSrc = newImageOrSrc;
  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. }