|
0 |
<!DOCTYPE html>
|
|
1 |
<head>
|
|
2 |
<meta charset="utf-8">
|
|
3 |
<title>Hanging a Canvas</title>
|
|
4 |
<style>
|
|
5 |
header {
|
|
6 |
background: goldenrod;
|
|
7 |
}
|
|
8 |
article {
|
|
9 |
width: 100%;
|
|
10 |
text-align: center;
|
|
11 |
}
|
|
12 |
</style>
|
|
13 |
</head>
|
|
14 |
<body>
|
|
15 |
<header>
|
|
16 |
<h1>Hanging a Canvas</h1>
|
|
17 |
<i></i>
|
|
18 |
</header>
|
|
19 |
<article>
|
|
20 |
<canvas id="canvas">
|
|
21 |
Your browser doesn't support displaying an HTML5 canvas.
|
|
22 |
</canvas>
|
|
23 |
</article>
|
|
24 |
</body>
|
|
25 |
<script>
|
|
26 |
var resizeCanvas = function() {
|
|
27 |
var desiredWidth = 640;
|
|
28 |
var desiredHeight = 400;
|
|
29 |
var rect = canvas.parentElement.getBoundingClientRect();
|
|
30 |
var absTop = Math.round(rect.top + window.pageYOffset);
|
|
31 |
var absLeft = Math.round(rect.left + window.pageXOffset);
|
|
32 |
var html = document.documentElement;
|
|
33 |
var availWidth = html.clientWidth - absLeft * 2;
|
|
34 |
var availHeight = html.clientHeight - (absTop + absLeft * 2);
|
|
35 |
var widthFactor = desiredWidth / availWidth;
|
|
36 |
var heightFactor = desiredHeight / availHeight;
|
|
37 |
var scale = 1 / Math.max(widthFactor, heightFactor);
|
|
38 |
|
|
39 |
// If you don't mind expanding the canvas, you can leave out
|
|
40 |
// this scale-clipping guard. The aspect ratio will still be preserved.
|
|
41 |
scale = scale > 1 ? 1 : scale;
|
|
42 |
|
|
43 |
var newWidth = Math.trunc(desiredWidth * scale);
|
|
44 |
var newHeight = Math.trunc(desiredHeight * scale);
|
|
45 |
if (canvas.width !== newWidth || canvas.height !== newHeight) {
|
|
46 |
canvas.width = newWidth;
|
|
47 |
canvas.height = newHeight;
|
|
48 |
// and redraw
|
|
49 |
var ctx = canvas.getContext('2d');
|
|
50 |
ctx.fillStyle = 'red';
|
|
51 |
ctx.fillRect(0, 0, canvas.width / 2, canvas.height / 2);
|
|
52 |
ctx.fillStyle = 'blue';
|
|
53 |
ctx.fillRect(canvas.width / 2, canvas.height / 2, canvas.width, canvas.height);
|
|
54 |
}
|
|
55 |
|
|
56 |
// If you want to center the canvas vertically, here's one way:
|
|
57 |
// figure out how much space you have available below it, and give
|
|
58 |
// the canvas a top-margin of 1/2 that.
|
|
59 |
if (availHeight > canvas.height) {
|
|
60 |
canvas.style.marginTop = Math.round((availHeight - canvas.height) / 2) + "px";
|
|
61 |
}
|
|
62 |
|
|
63 |
document.getElementsByTagName('i')[0].innerHTML = (
|
|
64 |
'(available: ' + availWidth + 'x' + availHeight + ', ' +
|
|
65 |
'scale: ' + scale + ', ' +
|
|
66 |
'result: ' + canvas.width + 'x' + canvas.height + ')'
|
|
67 |
);
|
|
68 |
};
|
|
69 |
|
|
70 |
window.addEventListener("load", resizeCanvas);
|
|
71 |
window.addEventListener("resize", resizeCanvas);
|
|
72 |
</script>
|