image.js
2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var LRU = require("../../core/LRU");
var globalImageCache = new LRU(50);
/**
* @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
* @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
*/
function findExistImage(newImageOrSrc) {
if (typeof newImageOrSrc === 'string') {
var cachedImgObj = globalImageCache.get(newImageOrSrc);
return cachedImgObj && cachedImgObj.image;
} else {
return newImageOrSrc;
}
}
/**
* Caution: User should cache loaded images, but not just count on LRU.
* Consider if required images more than LRU size, will dead loop occur?
*
* @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
* @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
* @param {module:zrender/Element} [hostEl] For calling `dirty`.
* @param {Function} [cb] params: (image, cbPayload)
* @param {Object} [cbPayload] Payload on cb calling.
* @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
*/
function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
if (!newImageOrSrc) {
return image;
} else if (typeof newImageOrSrc === 'string') {
// Image should not be loaded repeatly.
if (image && image.__zrImageSrc === newImageOrSrc || !hostEl) {
return image;
} // Only when there is no existent image or existent image src
// is different, this method is responsible for load.
var cachedImgObj = globalImageCache.get(newImageOrSrc);
var pendingWrap = {
hostEl: hostEl,
cb: cb,
cbPayload: cbPayload
};
if (cachedImgObj) {
image = cachedImgObj.image;
!isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
} else {
image = new Image();
image.onload = image.onerror = imageOnLoad;
globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
image: image,
pending: [pendingWrap]
});
image.src = image.__zrImageSrc = newImageOrSrc;
}
return image;
} // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
else {
return newImageOrSrc;
}
}
function imageOnLoad() {
var cachedImgObj = this.__cachedImgObj;
this.onload = this.onerror = this.__cachedImgObj = null;
for (var i = 0; i < cachedImgObj.pending.length; i++) {
var pendingWrap = cachedImgObj.pending[i];
var cb = pendingWrap.cb;
cb && cb(this, pendingWrap.cbPayload);
pendingWrap.hostEl.dirty();
}
cachedImgObj.pending.length = 0;
}
function isImageReady(image) {
return image && image.width && image.height;
}
exports.findExistImage = findExistImage;
exports.createOrUpdateImage = createOrUpdateImage;
exports.isImageReady = isImageReady;