-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvas.html
116 lines (99 loc) · 2.77 KB
/
canvas.html
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
108
109
110
111
112
113
114
115
116
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Image Optimizer</title>
<style>
main {
width: 1216px;
margin: 0 auto;
}
</style>
</head>
<body>
<main>
<h1>Canvas version</h1>
<nav>
<a href="/">Default</a>
<a href="/dom">DOM</a>
<a href="/canvas">Canvas</a>
</nav>
</main>
<script>
if (location.port === "" && location.protocol === "https:") {
document
.querySelectorAll("a")
.forEach(
(link) => (link.href = "/img-optimizer" + link.getAttribute("href"))
);
}
</script>
<script>
const IMAGE_SIZE = 300;
const IMAGE_MARGIN = 4;
const IMAGE_COUNT = 40;
const IMAGES_IN_ROW = 4;
let offsetX = 0;
let offsetY = -IMAGE_SIZE - 4;
function imgLoad(imgUrl) {
return new Promise((resolve) => {
const img = new Image();
img.src = imgUrl;
img.onload = () => {
resolve(img);
};
});
}
async function imgDraw(ctx) {
for (let i = 0; i < IMAGE_COUNT; i++) {
const img = await imgLoad(`assets/${i + 1}.jpg`);
const origWidth = img.naturalWidth;
const origHeight = img.naturalHeight;
let x, y;
let scaleWidth = IMAGE_SIZE;
let scaleHeight = IMAGE_SIZE;
if (origWidth > origHeight) {
x = (origWidth - origHeight) / 2;
y = 0;
} else {
x = 0;
y = (origHeight - origWidth) / 2;
}
if (i % 4 === 0) {
offsetX = 0;
offsetY += IMAGE_SIZE + 4;
} else {
offsetX += IMAGE_SIZE + 4;
}
ctx.drawImage(
img,
x,
y,
origWidth - x * 2,
origHeight - y * 2,
offsetX,
offsetY,
scaleWidth,
scaleHeight
);
}
}
document.addEventListener("DOMContentLoaded", async () => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width =
IMAGE_SIZE * IMAGES_IN_ROW + IMAGES_IN_ROW * IMAGE_MARGIN;
canvas.height =
IMAGE_SIZE * (IMAGE_COUNT / IMAGES_IN_ROW) +
(IMAGE_COUNT / IMAGES_IN_ROW - 1) * IMAGE_MARGIN;
ctx.imageSmoothingQuality = "high";
document.querySelector("main").appendChild(canvas);
console.time("imgDraw");
await imgDraw(ctx);
console.timeEnd("imgDraw");
});
</script>
</body>
</html>