-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
load_sprite.js
67 lines (57 loc) · 2.11 KB
/
load_sprite.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
// @flow
import {getJSON, getImage, ResourceType} from '../util/ajax';
import browser from '../util/browser';
import {RGBAImage} from '../util/image';
import type {StyleImage} from './style_image';
import type {RequestManager} from '../util/mapbox';
import type {Callback} from '../types/callback';
import type {Cancelable} from '../types/cancelable';
export default function(baseURL: string,
requestManager: RequestManager,
callback: Callback<{[string]: StyleImage}>): Cancelable {
let json: any, image, error;
const format = browser.devicePixelRatio > 1 ? '@2x' : '';
let jsonRequest = getJSON(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.json'), ResourceType.SpriteJSON), (err: ?Error, data: ?Object) => {
jsonRequest = null;
if (!error) {
error = err;
json = data;
maybeComplete();
}
});
let imageRequest = getImage(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.png'), ResourceType.SpriteImage), (err, img) => {
imageRequest = null;
if (!error) {
error = err;
image = img;
maybeComplete();
}
});
function maybeComplete() {
if (error) {
callback(error);
} else if (json && image) {
const imageData = browser.getImageData(image);
const result = {};
for (const id in json) {
const {width, height, x, y, sdf, pixelRatio} = json[id];
const data = new RGBAImage({width, height});
RGBAImage.copy(imageData, data, {x, y}, {x: 0, y: 0}, {width, height});
result[id] = {data, pixelRatio, sdf};
}
callback(null, result);
}
}
return {
cancel() {
if (jsonRequest) {
jsonRequest.cancel();
jsonRequest = null;
}
if (imageRequest) {
imageRequest.cancel();
imageRequest = null;
}
}
};
}