/
loadImage.js
102 lines (87 loc) · 3.11 KB
/
loadImage.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
/*global define*/
define([
'../ThirdParty/when',
'./defaultValue',
'./defined',
'./DeveloperError',
'./isCrossOriginUrl',
'./TrustedServers'
], function(
when,
defaultValue,
defined,
DeveloperError,
isCrossOriginUrl,
TrustedServers) {
'use strict';
var dataUriRegex = /^data:/;
/**
* Asynchronously loads the given image URL. Returns a promise that will resolve to
* an {@link Image} once loaded, or reject if the image failed to load.
*
* @exports loadImage
*
* @param {String|Promise.<String>} url The source of the image, or a promise for the URL.
* @param {Boolean} [allowCrossOrigin=true] Whether to request the image using Cross-Origin
* Resource Sharing (CORS). CORS is only actually used if the image URL is actually cross-origin.
* Data URIs are never requested using CORS.
* @returns {Promise.<Image>} a promise that will resolve to the requested data when loaded.
*
*
* @example
* // load a single image asynchronously
* Cesium.loadImage('some/image/url.png').then(function(image) {
* // use the loaded image
* }).otherwise(function(error) {
* // an error occurred
* });
*
* // load several images in parallel
* when.all([loadImage('image1.png'), loadImage('image2.png')]).then(function(images) {
* // images is an array containing all the loaded images
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
function loadImage(url, allowCrossOrigin) {
//>>includeStart('debug', pragmas.debug);
if (!defined(url)) {
throw new DeveloperError('url is required.');
}
//>>includeEnd('debug');
allowCrossOrigin = defaultValue(allowCrossOrigin, true);
return when(url, function(url) {
var crossOrigin;
// data URIs can't have allowCrossOrigin set.
if (dataUriRegex.test(url) || !allowCrossOrigin) {
crossOrigin = false;
} else {
crossOrigin = isCrossOriginUrl(url);
}
var deferred = when.defer();
loadImage.createImage(url, crossOrigin, deferred);
return deferred.promise;
});
}
// This is broken out into a separate function so that it can be mocked for testing purposes.
loadImage.createImage = function(url, crossOrigin, deferred) {
var image = new Image();
image.onload = function() {
deferred.resolve(image);
};
image.onerror = function(e) {
deferred.reject(e);
};
if (crossOrigin) {
if (TrustedServers.contains(url)) {
image.crossOrigin = 'use-credentials';
} else {
image.crossOrigin = '';
}
}
image.src = url;
};
loadImage.defaultCreateImage = loadImage.createImage;
return loadImage;
});