Reputation: 686
According to documentation for Javascript's window.innerWidth and window.innerHeight properties, both are calculated without toolbars and scroll bars. However, when I try to set a div element and a canvas element to be the same size as the window, both elements have excess on their width and the height properties. How do I go about fixing this?
HTML
<body>
<div id="gameScreen">
<canvas id="basemap"></canvas>
</div>
</body>
CSS
html, body{
margin: 0;
padding: 0;
}
#gameScreen{
margin: 0;
padding: 0;
border: 1px solid black;
}
#basemap{
margin: 0;
padding: 0;
background-color: red;
}
JS
function sizePage(){
var gameScreen = document.getElementById("gameScreen");
var basemap = document.getElementById("basemap");
var canvasWidth = window.innerWidth;
var cnavasHeight = window.innerHeight;
gameScreen.style.width = canvasWidth +"px";
gameScreen.style.height = cnavasHeight +"px";
basemap.width = canvasWidth;
basemap.height = cnavasHeight;
}
sizePage();
window.addEventListener("resize", function(){
sizePage();
})
Upvotes: 0
Views: 2573
Reputation: 190
I did some try and error process and this seems to work:
first do some css to set the body to full screen:
(if you want to add more html stuff uder the canvas use a div insted of body)
body {
margin: 0;
height: 100vh;
width: 100vw;
}
canvas {
/* setting display to block is really important*/
display: block;
}
now javascript to resize the canvas to that fullscreen body:
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
optional optimization:
as now for the cherry on the top add a responsive meta tag in the<head></head>
<!--this is optional-->
<meta name="viewport" content="width=device-width, initial-scale=1">
Upvotes: 2