forked from exupero/saveSvgAsPng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
saveSvgAsPng.js
267 lines (236 loc) · 8.18 KB
/
saveSvgAsPng.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
(function() {
var out$ = typeof exports != 'undefined' && exports || typeof define != 'undefined' && {} || this;
var doctype = '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "https://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
function isElement(obj) {
return obj instanceof HTMLElement || obj instanceof SVGElement;
}
function requireDomNode(el) {
if (!isElement(el)) {
throw new Error('an HTMLElement or SVGElement is required; got ' + el);
}
}
function isExternal(url) {
return url && url.lastIndexOf('http',0) == 0 && url.lastIndexOf(window.location.host) == -1;
}
function inlineImages(el, callback) {
requireDomNode(el);
var images = el.querySelectorAll('image'),
left = images.length,
checkDone = function() {
if (left === 0) {
callback();
}
};
checkDone();
for (var i = 0; i < images.length; i++) {
(function(image) {
var href = image.getAttributeNS("https://www.w3.org/1999/xlink", "href");
if (href) {
if (isExternal(href.value)) {
console.warn("Cannot render embedded images linking to external hosts: "+href.value);
return;
}
}
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
href = href || image.getAttribute('href');
if (href) {
img.src = href;
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
image.setAttributeNS("https://www.w3.org/1999/xlink", "href", canvas.toDataURL('image/png'));
left--;
checkDone();
}
img.onerror = function() {
console.log("Could not load "+href);
left--;
checkDone();
}
} else {
left--;
checkDone();
}
})(images[i]);
}
}
function styles(el, selectorRemap) {
var css = "";
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
try {
var rules = sheets[i].cssRules;
} catch (e) {
console.warn("Stylesheet could not be loaded: "+sheets[i].href);
continue;
}
if (rules != null) {
for (var j = 0; j < rules.length; j++) {
var rule = rules[j];
if (typeof(rule.style) != "undefined") {
var match, selectorText;
try {
selectorText = rule.selectorText;
} catch(err) {
console.warn('The following CSS rule has an invalid selector: "' + rule + '"', err);
}
try {
if (selectorText) {
match = el.querySelector(selectorText);
}
} catch(err) {
console.warn('Invalid CSS selector "' + selectorText + '"', err);
}
if (match) {
var selector = selectorRemap ? selectorRemap(rule.selectorText) : rule.selectorText;
css += selector + " { " + rule.style.cssText + " }\n";
} else if(rule.cssText.match(/^@font-face/)) {
css += rule.cssText + '\n';
}
}
}
}
}
return css;
}
function getDimension(el, clone, dim) {
var v = (el.viewBox && el.viewBox.baseVal && el.viewBox.baseVal[dim]) ||
(clone.getAttribute(dim) !== null && !clone.getAttribute(dim).match(/%$/) && parseInt(clone.getAttribute(dim))) ||
el.getBoundingClientRect()[dim] ||
parseInt(clone.style[dim]) ||
parseInt(window.getComputedStyle(el).getPropertyValue(dim));
return (typeof v === 'undefined' || v === null || isNaN(parseFloat(v))) ? 0 : v;
}
function reEncode(data) {
data = encodeURIComponent(data);
data = data.replace(/%([0-9A-F]{2})/g, function(match, p1) {
var c = String.fromCharCode('0x'+p1);
return c === '%' ? '%25' : c;
});
return decodeURIComponent(data);
}
out$.svgAsDataUri = function(el, options, cb) {
requireDomNode(el);
options = options || {};
options.scale = options.scale || 1;
var xmlns = "https://www.w3.org/2000/xmlns/";
inlineImages(el, function() {
var outer = document.createElement("div");
var clone = el.cloneNode(true);
var width, height;
if(el.tagName == 'svg') {
width = options.width || getDimension(el, clone, 'width');
height = options.height || getDimension(el, clone, 'height');
} else if(el.getBBox) {
var box = el.getBBox();
width = box.x + box.width;
height = box.y + box.height;
clone.setAttribute('transform', clone.getAttribute('transform').replace(/translate\(.*?\)/, ''));
var svg = document.createElementNS('https://www.w3.org/2000/svg','svg')
svg.appendChild(clone)
clone = svg;
} else {
console.error('Attempted to render non-SVG element', el);
return;
}
clone.setAttribute("version", "1.1");
if (!clone.getAttribute('xmlns')) {
clone.setAttributeNS(xmlns, "xmlns", "https://www.w3.org/2000/svg");
}
if (!clone.getAttribute('xmlns:xlink')) {
clone.setAttributeNS(xmlns, "xmlns:xlink", "https://www.w3.org/1999/xlink");
}
clone.setAttribute("width", width * options.scale);
clone.setAttribute("height", height * options.scale);
clone.setAttribute("viewBox", [
options.left || 0,
options.top || 0,
width,
height
].join(" "));
var fos = clone.querySelectorAll('foreignObject > *');
for (var i = 0; i < fos.length; i++) {
fos[i].setAttributeNS(xmlns, "xmlns", "https://www.w3.org/1999/xhtml");
}
outer.appendChild(clone);
var css = styles(el, options.selectorRemap);
var s = document.createElement('style');
s.setAttribute('type', 'text/css');
s.innerHTML = "<![CDATA[\n" + css + "\n]]>";
var defs = document.createElement('defs');
defs.appendChild(s);
clone.insertBefore(defs, clone.firstChild);
var svg = doctype + outer.innerHTML;
var uri = 'data:image/svg+xml;base64,' + window.btoa(reEncode(svg));
if (cb) {
cb(uri);
}
});
}
out$.svgAsPngUri = function(el, options, cb) {
requireDomNode(el);
out$.svgAsDataUri(el, options, function(uri) {
var image = new Image();
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
if(options && options.backgroundColor){
context.fillStyle = options.backgroundColor;
context.fillRect(0, 0, canvas.width, canvas.height);
}
context.drawImage(image, 0, 0);
var a = document.createElement('a'), png;
try {
png = canvas.toDataURL('image/png');
} catch (e) {
if ((typeof SecurityError !== 'undefined' && e instanceof SecurityError) || e.name == "SecurityError") {
console.error("Rendered SVG images cannot be downloaded in this browser.");
return;
} else {
throw e;
}
}
cb(png);
}
image.onerror = function(error) {
console.error('There was an error loading the data URI as an image', error);
}
image.src = uri;
});
}
function download(name, uri) {
var a = document.createElement('a');
a.download = name;
a.href = uri;
document.body.appendChild(a);
a.addEventListener("click", function(e) {
a.parentNode.removeChild(a);
});
a.click();
}
out$.saveSvg = function(el, name, options) {
requireDomNode(el);
options = options || {};
out$.svgAsDataUri(el, options, function(uri) {
download(name, uri);
});
}
out$.saveSvgAsPng = function(el, name, options) {
requireDomNode(el);
options = options || {};
out$.svgAsPngUri(el, options, function(uri) {
download(name, uri);
});
}
// if define is defined create as an AMD module
if (typeof define !== 'undefined') {
define(function() {
return out$;
});
}
})();