Permalink
Newer
100644
89 lines (70 sloc)
2.42 KB
5
var icon = {};
6
7
function changeColors(iconData, fillColor, strokeColor) {
8
var re;
9
10
if (fillColor) {
11
re = /(<!ENTITY fill_color ")(.*)(">)/;
12
iconData = iconData.replace(re, "$1" + fillColor + "$3");
13
}
14
15
if (strokeColor) {
16
re = /(<!ENTITY stroke_color ")(.*)(">)/;
17
iconData = iconData.replace(re, "$1" + strokeColor + "$3");
18
}
19
20
return iconData;
21
}
22
23
icon.load = function (iconInfo, callback) {
24
var source;
25
var dataHeader = "data:image/svg+xml,";
26
27
if ("uri" in iconInfo) {
28
source = iconInfo.uri;
29
} else if ("name" in iconInfo) {
30
source = "lib/graphics/icons/" + iconInfo.name + ".svg";
31
}
32
33
var fillColor = iconInfo.fillColor;
34
var strokeColor = iconInfo.strokeColor;
35
36
// If source is already a data uri, read it instead of doing
37
// the XMLHttpRequest
38
if (source.substring(0, 4) == 'data') {
39
var iconData = unescape(source.slice(dataHeader.length));
40
var newData = changeColors(iconData, fillColor, strokeColor);
41
callback(dataHeader + escape(newData));
42
return;
43
}
44
45
var client = new XMLHttpRequest();
46
47
client.onload = function () {
48
var iconData = this.responseText;
49
var newData = changeColors(iconData, fillColor, strokeColor);
50
callback(dataHeader + escape(newData));
51
};
54
client.send();
55
};
56
57
function getBackgroundURL(elem) {
58
var style = elem.currentStyle || window.getComputedStyle(elem, '');
59
// Remove prefix 'url(' and suffix ')' before return
60
var res = style.backgroundImage.slice(4, -1);
61
var last = res.length-1;
62
if (res[0] == '"' && res[last] == '"') {
63
res = res.slice(1, last);
64
}
65
return res;
66
}
67
68
function setBackgroundURL(elem, url) {
69
elem.style.backgroundImage = "url('" + url + "')";
70
}
71
72
icon.colorize = function (elem, colors, callback) {
73
var iconInfo = {
74
"uri": getBackgroundURL(elem),
75
"strokeColor": colors.stroke,
76
"fillColor": colors.fill