-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Image.js
341 lines (313 loc) · 9.82 KB
/
Image.js
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
/**
* @module ol/Image
*/
import EventTarget from './events/Target.js';
import EventType from './events/EventType.js';
import ImageState from './ImageState.js';
import {CREATE_IMAGE_BITMAP, IMAGE_DECODE} from './has.js';
import {listenOnce, unlistenByKey} from './events.js';
import {toPromise} from './functions.js';
/**
* A function that takes an {@link module:ol/Image~ImageWrapper} for the image and a
* `{string}` for the src as arguments. It is supposed to make it so the
* underlying image {@link module:ol/Image~ImageWrapper#getImage} is assigned the
* content specified by the src. If not specified, the default is
*
* function(image, src) {
* image.getImage().src = src;
* }
*
* Providing a custom `imageLoadFunction` can be useful to load images with
* post requests or - in general - through XHR requests, where the src of the
* image element would be set to a data URI when the content is loaded.
*
* @typedef {function(import("./Image.js").default, string): void} LoadFunction
* @api
*/
/**
* @typedef {Object} ImageObject
* @property {import("./extent.js").Extent} [extent] Extent, if different from the requested one.
* @property {import("./resolution.js").ResolutionLike} [resolution] Resolution, if different from the requested one.
* When x and y resolution are different, use the array type (`[xResolution, yResolution]`).
* @property {number} [pixelRatio] Pixel ratio, if different from the requested one.
* @property {import('./DataTile.js').ImageLike} image Image.
*/
/**
* Loader function used for image sources. Receives extent, resolution and pixel ratio as arguments.
* For images that cover any extent and resolution (static images), the loader function should not accept
* any arguments. The function returns an {@link import("./DataTile.js").ImageLike image}, an
* {@link import("./Image.js").ImageObject image object}, or a promise for the same.
* For loaders that generate images, the promise should not resolve until the image is loaded.
* If the returned image does not match the extent, resolution or pixel ratio passed to the loader,
* it has to return an {@link import("./Image.js").ImageObject image object} with the `image` and the
* correct `extent`, `resolution` and `pixelRatio`.
*
* @typedef {function(import("./extent.js").Extent, number, number, (function(HTMLImageElement, string): void)=): import("./DataTile.js").ImageLike|ImageObject|Promise<import("./DataTile.js").ImageLike|ImageObject>} Loader
* @api
*/
/**
* Loader function used for image sources. Receives extent, resolution and pixel ratio as arguments.
* The function returns a promise for an {@link import("./Image.js").ImageObject image object}.
*
* @typedef {function(import("./extent.js").Extent, number, number, (function(HTMLImageElement, string): void)=): import("./DataTile.js").ImageLike|ImageObject|Promise<import("./DataTile.js").ImageLike|ImageObject>} ImageObjectPromiseLoader
*/
class ImageWrapper extends EventTarget {
/**
* @param {import("./extent.js").Extent} extent Extent.
* @param {number|Array<number>|undefined} resolution Resolution. If provided as array, x and y
* resolution will be assumed.
* @param {number} pixelRatio Pixel ratio.
* @param {import("./ImageState.js").default|import("./Image.js").Loader} stateOrLoader State.
*/
constructor(extent, resolution, pixelRatio, stateOrLoader) {
super();
/**
* @protected
* @type {import("./extent.js").Extent}
*/
this.extent = extent;
/**
* @private
* @type {number}
*/
this.pixelRatio_ = pixelRatio;
/**
* @protected
* @type {number|Array<number>|undefined}
*/
this.resolution = resolution;
/**
* @protected
* @type {import("./ImageState.js").default}
*/
this.state =
typeof stateOrLoader === 'function' ? ImageState.IDLE : stateOrLoader;
/**
* @private
* @type {import('./DataTile.js').ImageLike|null}
*/
this.image_ = null;
/**
* @protected
* @type {import("./Image.js").Loader}
*/
this.loader = typeof stateOrLoader === 'function' ? stateOrLoader : null;
}
/**
* @protected
*/
changed() {
this.dispatchEvent(EventType.CHANGE);
}
/**
* @return {import("./extent.js").Extent} Extent.
*/
getExtent() {
return this.extent;
}
/**
* @return {import('./DataTile.js').ImageLike} Image.
*/
getImage() {
return this.image_;
}
/**
* @return {number} PixelRatio.
*/
getPixelRatio() {
return this.pixelRatio_;
}
/**
* @return {number|Array<number>} Resolution.
*/
getResolution() {
return /** @type {number} */ (this.resolution);
}
/**
* @return {import("./ImageState.js").default} State.
*/
getState() {
return this.state;
}
/**
* Load not yet loaded URI.
*/
load() {
if (this.state == ImageState.IDLE) {
if (this.loader) {
this.state = ImageState.LOADING;
this.changed();
const resolution = this.getResolution();
const requestResolution = Array.isArray(resolution)
? resolution[0]
: resolution;
toPromise(() =>
this.loader(
this.getExtent(),
requestResolution,
this.getPixelRatio(),
),
)
.then((image) => {
if ('image' in image) {
this.image_ = image.image;
}
if ('extent' in image) {
this.extent = image.extent;
}
if ('resolution' in image) {
this.resolution = image.resolution;
}
if ('pixelRatio' in image) {
this.pixelRatio_ = image.pixelRatio;
}
if (
image instanceof HTMLImageElement ||
image instanceof ImageBitmap ||
image instanceof HTMLCanvasElement ||
image instanceof HTMLVideoElement
) {
this.image_ = image;
}
this.state = ImageState.LOADED;
})
.catch((error) => {
this.state = ImageState.ERROR;
console.error(error); // eslint-disable-line no-console
})
.finally(() => this.changed());
}
}
}
/**
* @param {import('./DataTile.js').ImageLike} image The image.
*/
setImage(image) {
this.image_ = image;
}
/**
* @param {number|Array<number>} resolution Resolution.
*/
setResolution(resolution) {
this.resolution = resolution;
}
}
/**
* @param {import('./DataTile.js').ImageLike} image Image element.
* @param {function():any} loadHandler Load callback function.
* @param {function():any} errorHandler Error callback function.
* @return {function():void} Callback to stop listening.
*/
export function listenImage(image, loadHandler, errorHandler) {
const img = /** @type {HTMLImageElement} */ (image);
let listening = true;
let decoding = false;
let loaded = false;
const listenerKeys = [
listenOnce(img, EventType.LOAD, function () {
loaded = true;
if (!decoding) {
loadHandler();
}
}),
];
if (img.src && IMAGE_DECODE) {
decoding = true;
img
.decode()
.then(function () {
if (listening) {
loadHandler();
}
})
.catch(function (error) {
if (listening) {
if (loaded) {
loadHandler();
} else {
errorHandler();
}
}
});
} else {
listenerKeys.push(listenOnce(img, EventType.ERROR, errorHandler));
}
return function unlisten() {
listening = false;
listenerKeys.forEach(unlistenByKey);
};
}
/**
* Loads an image.
* @param {HTMLImageElement} image Image, not yet loaded.
* @param {string} [src] `src` attribute of the image. Optional, not required if already present.
* @return {Promise<HTMLImageElement>} Promise resolving to an `HTMLImageElement`.
* @api
*/
export function load(image, src) {
return new Promise((resolve, reject) => {
function handleLoad() {
unlisten();
resolve(image);
}
function handleError() {
unlisten();
reject(new Error('Image load error'));
}
function unlisten() {
image.removeEventListener('load', handleLoad);
image.removeEventListener('error', handleError);
}
image.addEventListener('load', handleLoad);
image.addEventListener('error', handleError);
if (src) {
image.src = src;
}
});
}
/**
* @param {HTMLImageElement} image Image, not yet loaded.
* @param {string} [src] `src` attribute of the image. Optional, not required if already present.
* @return {Promise<HTMLImageElement>} Promise resolving to an `HTMLImageElement`.
*/
export function decodeFallback(image, src) {
if (src) {
image.src = src;
}
return image.src && IMAGE_DECODE
? new Promise((resolve, reject) =>
image
.decode()
.then(() => resolve(image))
.catch((e) =>
image.complete && image.width ? resolve(image) : reject(e),
),
)
: load(image);
}
/**
* Loads an image and decodes it to an `ImageBitmap` if `createImageBitmap()` is supported. Returns
* the loaded image otherwise.
* @param {HTMLImageElement} image Image, not yet loaded.
* @param {string} [src] `src` attribute of the image. Optional, not required if already present.
* @return {Promise<ImageBitmap|HTMLImageElement>} Promise resolving to an `ImageBitmap` or an
* `HTMLImageElement` if `createImageBitmap()` is not supported.
* @api
*/
export function decode(image, src) {
if (src) {
image.src = src;
}
return image.src && IMAGE_DECODE && CREATE_IMAGE_BITMAP
? image
.decode()
.then(() => createImageBitmap(image))
.catch((e) => {
if (image.complete && image.width) {
return image;
}
throw e;
})
: decodeFallback(image);
}
export default ImageWrapper;