-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathscaleToWindow.js
More file actions
77 lines (68 loc) · 2.51 KB
/
scaleToWindow.js
File metadata and controls
77 lines (68 loc) · 2.51 KB
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
function scaleToWindow(canvas, backgroundColor) {
var scaleX, scaleY, scale, center;
//1. Scale the canvas to the correct size
//Figure out the scale amount on each axis
scaleX = window.innerWidth / canvas.offsetWidth;
scaleY = window.innerHeight / canvas.offsetHeight;
//Scale the canvas based on whichever value is less: `scaleX` or `scaleY`
scale = Math.min(scaleX, scaleY);
canvas.style.transformOrigin = "0 0";
canvas.style.transform = "scale(" + scale + ")";
//2. Center the canvas.
//Decide whether to center the canvas vertically or horizontally.
//Wide canvases should be centered vertically, and
//square or tall canvases should be centered horizontally
if (canvas.offsetWidth > canvas.offsetHeight) {
if (canvas.offsetWidth * scale < window.innerWidth) {
center = "horizontally";
} else {
center = "vertically";
}
} else {
if (canvas.offsetHeight * scale < window.innerHeight) {
center = "vertically";
} else {
center = "horizontally";
}
}
//Center horizontally (for square or tall canvases)
var margin;
if (center === "horizontally") {
margin = (window.innerWidth - canvas.offsetWidth * scale) / 2;
canvas.style.marginTop = 0 + "px";
canvas.style.marginBottom = 0 + "px";
canvas.style.marginLeft = margin + "px";
canvas.style.marginRight = margin + "px";
}
//Center vertically (for wide canvases)
if (center === "vertically") {
margin = (window.innerHeight - canvas.offsetHeight * scale) / 2;
canvas.style.marginTop = margin + "px";
canvas.style.marginBottom = margin + "px";
canvas.style.marginLeft = 0 + "px";
canvas.style.marginRight = 0 + "px";
}
//3. Remove any padding from the canvas and body and set the canvas
//display style to "block"
canvas.style.paddingLeft = 0 + "px";
canvas.style.paddingRight = 0 + "px";
canvas.style.paddingTop = 0 + "px";
canvas.style.paddingBottom = 0 + "px";
canvas.style.display = "block";
//4. Set the color of the HTML body background
document.body.style.backgroundColor = backgroundColor;
//Fix some quirkiness in scaling for Safari
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("safari") != -1) {
if (ua.indexOf("chrome") > -1) {
// Chrome
} else {
// Safari
//canvas.style.maxHeight = "100%";
//canvas.style.minHeight = "100%";
}
}
//5. Return the `scale` value. This is important, because you'll nee this value
//for correct hit testing between the pointer and sprites
return scale;
}