-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
64 lines (55 loc) · 2.09 KB
/
Copy pathmain.js
File metadata and controls
64 lines (55 loc) · 2.09 KB
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
const img_box = document.querySelector(".img_box"),
img_box2 = document.querySelector(".img_box::before"),
previewimg = img_box.querySelector("img"),
fileInput = img_box.querySelector("input"),
reduceQty = document.getElementById("comQty"),
widthinput = document.querySelector(".size #width"),
heightinput = document.querySelector(".size #height"),
radioinput = document.querySelector(".option #resize"),
quality = document.querySelector(".option #reduce"),
downloadbtn = document.querySelector("#downloadbtn");
let ogimgratio;
widthinput.addEventListener("keyup", () => {
const height = radioinput.checked
? widthinput.value / ogimgratio
: heightinput.value;
heightinput.value = Math.floor(height);
});
heightinput.addEventListener("keyup", () => {
const width = radioinput.checked
? heightinput.value * ogimgratio
: widthinput.value;
widthinput.value = Math.floor(width);
});
const resizeAnddownload = () => {
const canvas = document.createElement("canvas");
const a = document.createElement("a");
const ctx = canvas.getContext("2d");
// const reduceQtyValue = reduceQty.value
//also pass 0.1 : 1.0 for more reduce quality (0.1 is lowest)
const imgQuality = quality.checked ? parseFloat(reduceQty.value) : 1.0;
// const imgQuality = quality.checked ? 0.1 : 1.0;
canvas.width = widthinput.value;
canvas.height = heightinput.value;
ctx.drawImage(previewimg, 0, 0, canvas.width, canvas.height);
//document.body.appendChild(canvas);
a.href = canvas.toDataURL("image/jpeg", imgQuality);
a.download = new Date().getTime();
a.click();
};
downloadbtn.addEventListener("click", resizeAnddownload);
fileInput.onchange = (e) =>{
const file = e.target.files[0];
if (!file) return;
previewimg.src = URL.createObjectURL(file);
previewimg.addEventListener("load", () => {
widthinput.value = previewimg.naturalWidth;
heightinput.value = previewimg.naturalHeight;
ogimgratio = previewimg.naturalWidth / previewimg.naturalHeight;
});
}
img_box.addEventListener("click", () => {
fileInput.click();
});
widthinput.value = '';
heightinput.value = '';