-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathreimg.js
98 lines (86 loc) · 3.08 KB
/
reimg.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
ReImg = {
OutputProcessor: function(encodedData, svgElement) {
var isPng = function() {
return encodedData.indexOf('data:image/png') === 0;
};
var downloadImage = function(data, filename) {
var a = document.createElement('a');
a.href = data;
a.download = filename;
document.body.appendChild(a);
a.click();
};
return {
toBase64: function() {
return encodedData;
},
toImg: function() {
var imgElement = document.createElement('img');
imgElement.src = encodedData;
return imgElement;
},
toCanvas: function(callback) {
var canvas = document.createElement('canvas');
var boundedRect = svgElement.getBoundingClientRect();
canvas.width = boundedRect.width;
canvas.height = boundedRect.height;
var canvasCtx = canvas.getContext('2d');
var img = this.toImg();
img.onload = function() {
canvasCtx.drawImage(img, 0, 0);
callback(canvas);
};
},
toPng: function() {
if (isPng()) {
var img = document.createElement('img');
img.src = encodedData;
return img;
}
this.toCanvas(function(canvas) {
var img = document.createElement('img');
img.src = canvas.toDataURL();
return img;
});
},
toJpeg: function(quality) { // quality should be between 0-1
quality = quality || 1.0;
(function(q) {
this.toCanvas(function(canvas) {
var img = document.createElement('img');
img.src = canvas.toDataURL('image/jpeg', q);
return img;
});
})(quality);
},
downloadPng: function(filename) {
filename = filename || 'image.png';
if (isPng()) {
// it's a canvas already
downloadImage(encodedData, filename);
return;
}
// convert to canvas first
this.toCanvas(function(canvas) {
downloadImage(canvas.toDataURL(), filename);
});
}
};
},
fromSvg: function(svgElement) {
var svgString = new XMLSerializer().serializeToString(svgElement);
return new this.OutputProcessor('data:image/svg+xml;base64,' + window.btoa(svgString), svgElement);
},
fromCanvas: function(canvasElement) {
var dataUrl = canvasElement.toDataURL();
return new this.OutputProcessor(dataUrl);
}
};
if(typeof exports === 'object' && typeof module !== void 0) {
module.exports = {
ReImg:ReImg
};
}
else {
window.ReImg = ReImg;
}