This repository has been archived by the owner on Jun 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
util.js
93 lines (80 loc) · 2.39 KB
/
util.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
export function createCanvas() {
const canvas = document.createElement('canvas');
canvas.height = 800;
canvas.width = 800;
return canvas;
}
export function createImageFromUrl(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.width = 800;
img.height = 800;
img.src = url;
img.onload = () => resolve(img);
img.onerror = reject;
});
}
export function mergeImages(bottomImageUrl, topImageUrl) {
return new Promise((resolve, reject) => {
const canvas = createCanvas();
const ctx = canvas.getContext("2d");
Promise.all([createImageFromUrl(bottomImageUrl), createImageFromUrl(topImageUrl)])
.then( ([bottomImage, topImage]) => {
ctx.drawImage(bottomImage, 0, 0, 800, 800);
ctx.drawImage(topImage, 0, 0, 800, 800);
resolve(canvas.toDataURL("image/jpeg"));
}).catch(reject);
})
}
export function postToFacebook({accessToken, image, message, userID}) {
return new Promise((resolve, reject) => {
const form = new FormData();
form.append("access_token", accessToken);
form.append("message", message);
form.append("file", image);
apiRequest(`https://graph.facebook.com/${userID}/photos`, {
method: 'POST',
body: form
})
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});
});
}
export function apiRequest(url, options) {
return new Promise((resolve, reject)=> {
const defaultOptions = {
// Pass in the cookies; by default fetch doesn't send cookies and session
credentials: 'same-origin'
};
// Merge options
options = {...options, ...defaultOptions };
fetch(url, options)
.then(response => {
if (response.status >= 200 && response.status < 300) {
resolve();
} else {
const error = new Error(response.statusText)
error.response = response
reject(error);
}
})
.catch(err => {
err = err.data ? err : new Error('An error occurred while connecting.');
reject(err);
});
});
}
// http://stackoverflow.com/a/15754051
export function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: 'image/jpeg' });
}