-
Notifications
You must be signed in to change notification settings - Fork 1
/
how-to-keep-ratio.html
44 lines (39 loc) · 1.59 KB
/
how-to-keep-ratio.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>How to keep 1:1 aspect ratio for the child canvas element?</title>
<link type="text/css" rel="stylesheet" href="src/main.css" />
</head>
<body>
<div class="flexRoot">
<div class="status">Game #1 Score1:Score2</div>
<div class="parent" id="parent">
<canvas id="child"></canvas>
</div>
<div class="hint">A game hint to do this and that...</div>
</div>
<script>
const parentElement = document.getElementById("parent");
const childElement = document.getElementById("child");
const resizeObserver = new ResizeObserver((entries) => {
for (let entry of entries) {
const { width, height } = entry.contentRect;
const minDimension = Math.min(width, height);
const maxDimension = Math.max(width, height);
const diff = Math.floor((maxDimension - minDimension) / 2);
const paddingLeft = width > height ? diff : 0;
const paddingTop = width < height ? diff : 0;
childElement.style.width = `${minDimension}px`;
childElement.style.height = `${minDimension}px`;
childElement.style.transform = `translate(${paddingLeft}px, ${paddingTop}px)`;
console.log(
`parent ${width} x ${height} -> child ${childElement.style.width} x ${childElement.style.height} @ ${childElement.style.transform}`
);
}
});
resizeObserver.observe(parentElement);
</script>
</body>
</html>