-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfillerup.js
83 lines (71 loc) · 2.18 KB
/
fillerup.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
;(function() {
var fillRegex = /fill=['"].+?["']/;
function fillerup() {
var els = document.querySelectorAll('[data-fill]');
var i = 0;
var len = els.length;
for (i = 0; i < len; i++) {
fillSVG(els[i]);
}
}
function fillSVG(el) {
var fill = el.getAttribute('data-fill');
fill = fill === 'random' ? '#' + Math.floor(Math.random() * 16777215).toString(16) : fill;
var fn = el.tagName === 'IMG' ? fillImg : fillBg;
fn(el, fill);
}
function fillBg(el, fill) {
var style = window.getComputedStyle(el);
var uri = style.backgroundImage;
if (!uri || uri === 'none') return; // in cases where css is not yet loaded
var svg64 = uri.replace(/^.+base64,/, '').replace(/['"]?\)$/, '');
var xml = window.atob(svg64);
el.style.backgroundImage = 'url(' + getUri(xml, fill) + ')';
}
function getUri(xml, fill) {
var m = xml.match(fillRegex);
var fn = m && m.length ? regexReplace : addFill;
var color = fn(xml, fill);
return getDataUri(color);
}
function regexReplace(xml, fill) {
var svg = xml.replace(fillRegex, 'fill="' + fill + '"');
return svg;
}
function getDataUri(svg) {
var svg64 = window.btoa(svg);
return 'data:image/svg+xml;base64,' + svg64;
}
// fill when no fill yet exists
function addFill(xml, fill) {
var parser = new DOMParser();
var svgXML = parser.parseFromString(xml, 'text/xml');
var children = svgXML.childNodes;
// add fill attributes to all of the children
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType === 1) { // searches for element nodes
children[i].setAttribute('fill', fill);
}
}
return (new XMLSerializer()).serializeToString(svgXML);
}
function fillImg(el, fill) {
var src = el.getAttribute('src');
getSvg(src, function(xml) {
var uri = getUri(xml, fill);
el.setAttribute('src', uri);
});
}
function getSvg(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onload = function() {
cb(this.responseText);
};
xhr.onerror = function() {
console.warn('Attempt to download ' + url + ' failed.');
};
xhr.send();
}
fillerup();
})();