-
Notifications
You must be signed in to change notification settings - Fork 0
/
dom.html
124 lines (106 loc) · 2.87 KB
/
dom.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
117
118
119
120
121
122
123
124
<!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>
img {
width: 300px;
height: 300px;
margin-right: 4px;
}
main {
width: 1216px;
margin: 0 auto;
}
</style>
</head>
<body>
<main>
<h1>DOM 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_COUNT = 40;
const main = document.querySelector("main");
function imgLoad(imgUrl) {
return new Promise((resolve) => {
const img = new Image();
img.src = imgUrl;
img.onload = () => {
resolve(img);
};
});
}
function toBlob(canvas) {
return new Promise((resolve) => {
canvas.toBlob((blob) => {
const img = document.createElement("img");
const url = URL.createObjectURL(blob);
main.appendChild(img);
img.src = url;
img.onload = () => {
URL.revokeObjectURL(url);
resolve();
};
});
});
}
async function imgDraw(canvas, 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;
}
ctx.drawImage(
img,
x,
y,
origWidth - x * 2,
origHeight - y * 2,
0,
0,
scaleWidth,
scaleHeight
);
await toBlob(canvas);
}
}
document.addEventListener("DOMContentLoaded", async () => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = IMAGE_SIZE;
canvas.height = IMAGE_SIZE;
ctx.imageSmoothingQuality = "high";
console.time("imgDraw");
await imgDraw(canvas, ctx);
console.timeEnd("imgDraw");
});
</script>
</body>
</html>