-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathIconRequestor.js
More file actions
344 lines (317 loc) · 11.8 KB
/
Copy pathIconRequestor.js
File metadata and controls
344 lines (317 loc) · 11.8 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import { Marker, Util, formatResourceUrl, Browser } from 'maptalks';
import LRUCache from '../packer/LRUCache';
function isImageBitMap(img) {
return img && Browser.decodeImageInWorker && img instanceof ImageBitmap;
}
function isPowerOfTwo(value) {
return (value & (value - 1)) === 0 && value !== 0;
}
function getUVImageNearbySize(v) {
v = Math.round(v);
let size = 1;
while (size < v) {
size *= 2;
}
const d1 = Math.abs(v - size / 2), d2 = Math.abs(v - size);
if (d1 < d2) {
return size / 2;
}
return size;
}
function resizeUVImage(image) {
if (image.needResize) {
const { width, height } = image;
let w = width, h = height;
if (!isPowerOfTwo(width)) {
w = getUVImageNearbySize(width);
}
if (!isPowerOfTwo(height)) {
h = getUVImageNearbySize(height);
}
image.width = w;
image.height = h;
}
}
export default class IconRequestor {
//options.errorUrl : alt image when failing loading the icon
constructor(options) {
this.options = options || {};
this._requesting = {};
this._cache = new LRUCache(256, function () { });
const canvas = document.createElement('canvas');
this.ctx = canvas.getContext('2d', { willReadFrequently: true });
}
getIcons(icons, cb) {
if (!icons || !Object.keys(icons).length) {
cb(null, { icons: null });
return;
}
const urls = Object.keys(icons);
const images = {}, buffers = [];
let count = 0;
let current = 0;
const self = this;
function callback(url, size) {
images[url] = self._getCache(url, size);
if (images[url] && images[url] !== 'error') {
buffers.push(images[url].data.data.buffer);
} else {
delete images[url];
}
current++;
if (current === count) {
cb(null, { icons: images, buffers });
}
}
function complete(img) {
const requests = self._requesting[img.url];
for (let i = 0; i < requests.length; i++) {
requests[i].call(img, img.url, img.size);
}
delete self._requesting[img.url];
}
function onload() {
const ctx = self.ctx;
let width, height;
try {
resizeUVImage(this);
width = this.width;
height = this.height;
this.size[0] = width;
this.size[1] = height;
self._ensureMaxSize(null, this.size);
width = this.size[0];
height = this.size[1];
const canvas = ctx.canvas;
canvas.width = width;
canvas.height = height;
ctx.imageSmoothingEnabled = false;
ctx.drawImage(this, 0, 0, width, height);
// ctx.imageSmoothingEnabled = false;
// const canvas = ctx.canvas;
// resize(this, ctx);
const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
self._addCache(this.url, data, canvas.width, canvas.height);
} catch (err) {
//tainted canvas
console.warn(err);
}
complete(this);
}
function onerror(err) {
console.warn(`failed loading icon(${this.index}) at "${this.url}"`);
console.warn(err);
if (self.options.iconErrorUrl) {
this.src = self.options.iconErrorUrl;
} else {
self._addCache(this.url);
complete(this);
}
}
const urlModifier = this.options.urlModifier;
let hasRequests = false;
let marker;
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
const needResize = icons[url][2];
icons[url] = icons[url].slice(0, 2);
const size = icons[url];
this._ensureMaxSize(url, size);
const icon = this._getCache(url, size);
if (icon && icon !== 'error') {
images[url] = this._getCache(url, size);
continue;
} else if (icon === 'error') {
continue;
}
let symbol, realUrl = url;
if (url.indexOf('vector://') === 0) {
symbol = JSON.parse(url.substring('vector://'.length));
if (symbol.markerType === 'path') {
realUrl = Util.getMarkerPathBase64(symbol, symbol['markerWidth'], symbol['markerHeight']);
}
}
//Proxy address for handling icon resources, or manually injected resources
//realUrl may be imagebitmap/blob url/base64/etc.
realUrl = formatResourceUrl(realUrl);
if (url.indexOf('vector://') === 0 && symbol.markerType !== 'path') {
marker = marker || new Marker([0, 0]);
const { markerFill, markerLineColor } = symbol;
if (markerFill && Array.isArray(markerFill)) {
symbol.markerFill = convertColorArray(markerFill);
}
if (markerLineColor && Array.isArray(markerLineColor)) {
symbol.markerLineColor = convertColorArray(markerLineColor);
}
delete symbol.markerHorizontalAlignment;
delete symbol.markerVerticalAlignment;
delete symbol.markerDx;
delete symbol.markerDy;
delete symbol.markerPlacement;
delete symbol.markerFile;
symbol.markerWidth = size[0];
symbol.markerHeight = size[1];
marker.setSymbol(symbol);
const methodName = '_getSprite'.trim();
const sprite = marker[methodName]();
if (sprite) {
const canvas = sprite.canvas;
const width = canvas.width;
const height = canvas.height;
const data = canvas.getContext('2d', { willReadFrequently: true }).getImageData(0, 0, width, height).data;
images[url] = { data: { data: new Uint8ClampedArray(data), width, height }, url };
buffers.push(images[url].data.data.buffer);
this._addCache(url, data, width, height);
}
} else {
// fuzhenn/maptalks-designer#439
// canvas + svg存在bug: https://bugs.chromium.org/p/chromium/issues/detail?id=1142375
// 在canvas上绘制svg,调用getImageData时,data会发生变化
// 解决方法
// * 在requestor上增加cache缓存,保证同一个svg图片只会加载一次
// * Image 载入过程中的请求,先缓存在requesting,onload中集中处理
if (!this._requesting[url]) {
this._requesting[url] = [];
} else {
hasRequests = true;
count++;
this._requesting[url].push(callback);
continue;
}
this._requesting[url].push(callback);
const wrapImage = (img) => {
img.index = i;
img.size = size;
img.url = url;
img.crossOrigin = 'Anonymous';
img.needResize = needResize;
}
if (isImageBitMap(realUrl)) {
createImageBitmap(realUrl).then((img) => {
wrapImage(img)
onload.call(img);
}).catch((err) => {
onerror.call({ index: i, url }, err);
});
} else {
const img = new Image();
wrapImage(img)
img.onload = onload;
img.onerror = onerror;
img.onabort = onerror;
img.src = urlModifier && urlModifier(realUrl) || realUrl;
}
hasRequests = true;
count++;
}
}
if (!hasRequests) {
cb(null, { icons: images, buffers });
}
}
_hasCache(url, width, height) {
const icon = this._cache.get(url);
return icon && icon !== 'error' && icon.data.width >= width && icon.data.height >= height;
}
_addCache(url, data, width, height) {
if (!this._hasCache(url, width, height)) {
if (data) {
this._cache.add(url, { data: { data, width, height }, url });
} else {
this._cache.add(url, 'error');
}
}
}
_getCache(url, size) {
if (!this._hasCache(url, size[0], size[1])) {
return null;
}
const iconAtlas = this._cache.get(url);
if (!iconAtlas) {
return null;
}
if (iconAtlas === 'error') {
return iconAtlas;
}
return {
data: { data: new Uint8ClampedArray(iconAtlas.data.data), width: iconAtlas.data.width, height: iconAtlas.data.height },
url: iconAtlas.url
};
}
_ensureMaxSize(url, size) {
if (!size[0] || !size[1]) {
return;
}
const maxSize = this.options['maxSize'] || 2048;
let [width, height] = size;
const ratio = width / height;
if (url) {
const cached = this._cache.get(url);
if (cached && cached !== 'error') {
// 缓存中width或height更大时,则取更大的值
const { width: cachedWidth, height: cachedHeight } = cached.data;
if (cachedWidth > width) {
width = cachedWidth;
}
if (cachedHeight > height) {
height = cachedHeight;
}
}
}
if (width > maxSize) {
height = maxSize / ratio;
width = maxSize;
}
if (height > maxSize) {
width = maxSize * ratio;
height = maxSize;
}
size[0] = Math.floor(width);
size[1] = Math.floor(height);
}
}
// function resize(image, ctx) {
// const canvas = ctx.canvas;
// if (isPowerOfTwo(image.width) && isPowerOfTwo(image.height)) {
// canvas.width = image.width;
// canvas.height = image.height;
// ctx.drawImage(image, 0, 0, image.width, image.height);
// return image;
// }
// let width = image.width;
// let height = image.height;
// if (!isPowerOfTwo(width)) {
// width = ceilPowerOfTwo(width);
// }
// if (!isPowerOfTwo(height)) {
// height = ceilPowerOfTwo(height);
// }
// // const canvas = document.createElement('canvas');
// canvas.width = width;
// canvas.height = height;
// ctx.drawImage(image, 0, 0, width, height);
// const url = image.src;
// const idx = url.lastIndexOf('/') + 1;
// const filename = url.substring(idx);
// console.warn(`Texture(${filename})'s size is not power of two, resize from (${image.width}, ${image.height}) to (${width}, ${height})`);
// return canvas;
// }
// function isPowerOfTwo(value) {
// return (value & (value - 1)) === 0 && value !== 0;
// }
// function ceilPowerOfTwo(value) {
// return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
// }
function convertColorArray(color) {
if (color.length === 3) {
color.push(1);
}
return color.reduce((accumulator, v, idx) => {
if (idx < 3) {
accumulator += v * 255 + ',';
} else {
accumulator += v + ')';
}
return accumulator;
}, 'rgba(');
}