-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
107 lines (85 loc) · 2.24 KB
/
index.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
module.exports = function RckImage(image) {
const img = document.createElement("img");
img.setAttribute("crossOrigin", "anonymous");
let name;
let type;
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
const list = [
() => {
return new Promise((resolve) => {
img.addEventListener("load", () => {
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0, canvas.width, canvas.height);
resolve();
});
if (image instanceof File) {
name = image.name;
type = image.type;
img.setAttribute("src", URL.createObjectURL(image));
} else {
img.setAttribute("src", image);
}
});
},
];
async function execList() {
let response;
for (let item of list) {
response = await item();
}
return response;
}
const fn = {
resize({ size } = {}) {
list.push(() => {
return new Promise((resolve) => {
if (size) {
let width = img.width;
let height = img.height;
if (width > size && height > size) {
if (height < width) {
width = (size / height) * width;
height = size;
} else if (width <= height) {
height = (size / width) * height;
width = size;
}
}
canvas.width = width;
canvas.height = height;
context.drawImage(img, 0, 0, width, height);
resolve();
} else {
resolve();
}
});
});
return fn;
},
file({ type: t, quality = 1 } = {}) {
list.push(() => {
return new Promise((resolve) => {
canvas.toBlob(
(file) => {
resolve(
new File([file], name, {
type: file.type,
})
);
},
t || type,
quality
);
});
});
return execList();
},
async dataURL({ type: t, quality = 1 } = {}) {
await execList();
return canvas.toDataURL(t || type, quality);
},
};
return fn;
};