forked from shivshankar9/Student-portal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageresize.js
69 lines (49 loc) · 2.38 KB
/
imageresize.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
const fileInput = document.querySelector(".resizer__file");
const widthInput = document.querySelector(".resizer__input--width");
const heightInput = document.querySelector(".resizer__input--height");
const aspectToggle = document.querySelector(".resizer__aspect");
const canvas = document.querySelector(".resizer__canvas");
const canvasCtx = canvas.getContext("2d");
const downloadbtn = document.querySelector("#dwn-btn");
downloadbtn.addEventListener("click",function(){
});
let activeImage, originalWidthToHeightRatio;
fileInput.addEventListener("change", (e) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
openImage(reader.result);
});
reader.readAsDataURL(e.target.files[0]);
});
widthInput.addEventListener("change", () => {
if (!activeImage) return;
const heightValue = aspectToggle.checked
? widthInput.value / originalWidthToHeightRatio
: heightInput.value;
resize(widthInput.value, heightValue);
});
heightInput.addEventListener("change", () => {
if (!activeImage) return;
const widthValue = aspectToggle.checked
? heightInput.value * originalWidthToHeightRatio
: widthInput.value;
resize(widthValue, heightInput.value);
});
function openImage(imageSrc) {
activeImage = new Image();
activeImage.addEventListener("load", () => {
originalWidthToHeightRatio = activeImage.width / activeImage.height;
resize(activeImage.width, activeImage.height);
});
activeImage.src = imageSrc;
}
function resize(width, height) {
canvas.width = Math.floor(width);
canvas.height = Math.floor(height);
widthInput.value = Math.floor(width);
heightInput.value = Math.floor(height);
canvasCtx.drawImage(activeImage, 0, 0, Math.floor(width), Math.floor(height));
downloadbtn.style.display = "inline-block";
let dataurl = canvas.toDataURL(activeImage.type);
downloadbtn.href = dataurl;
}