-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.js
80 lines (69 loc) · 2.34 KB
/
image.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
const imageInput = document.getElementById("imageInput");
const combineButton = document.getElementById("combineButton");
const verticalCheckbox = document.getElementById("verticalCheckbox");
const horizontalCheckbox = document.getElementById("horizontalCheckbox");
const downloadLink = document.getElementById("downloadLink");
let images = [];
let combineDirection = "horizontal"; // Default direction
imageInput.addEventListener("change", (event) => {
images = Array.from(event.target.files);
});
verticalCheckbox.addEventListener("change", () => {
if (verticalCheckbox.checked) {
horizontalCheckbox.checked = false;
combineDirection = "vertical";
}
});
horizontalCheckbox.addEventListener("change", () => {
if (horizontalCheckbox.checked) {
verticalCheckbox.checked = false;
combineDirection = "horizontal";
}
});
combineButton.addEventListener("click", async () => {
if (images.length === 0) {
alert("Please select images first.");
return;
}
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const loadedImages = await Promise.all(
images.map((image) => loadImage(image))
);
const maxWidth = Math.max(...loadedImages.map((img) => img.width));
const totalHeight = loadedImages.reduce(
(height, img) => height + img.height,
0
);
if (combineDirection === "vertical") {
canvas.width = maxWidth;
canvas.height = totalHeight;
} else {
canvas.width = loadedImages.reduce((width, img) => width + img.width, 0);
canvas.height = Math.max(...loadedImages.map((img) => img.height));
}
let x = 0;
let y = 0;
loadedImages.forEach((img) => {
if (combineDirection === "vertical") {
x = (maxWidth - img.width) / 2;
ctx.drawImage(img, x, y, img.width, img.height);
y += img.height;
} else {
ctx.drawImage(img, x, y, img.width, img.height);
x += img.width;
}
});
const combinedImageURL = canvas.toDataURL();
const fileName = "combined_image.png";
downloadLink.href = combinedImageURL;
downloadLink.download = fileName;
downloadLink.style.display = "block";
});
function loadImage(file) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => resolve(img);
img.src = URL.createObjectURL(file);
});
}