画布未调整为窗口内部宽度&高度 [英] Canvas not sizing to window inner width & height
问题描述
根据Javascript的window.innerWidth和window.innerHeight属性的文档,计算时都没有工具栏和滚动条。但是,当我尝试将div元素和canvas元素设置为与窗口相同的大小时,两个元素的width和height属性都多余。我该如何解决呢?
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();
})
推荐答案
我做了一些尝试和错误处理,但这似乎可行:
I did some try and error process and this seems to work:
首先要做一些CSS设置正文到全屏显示:
(如果您想在画布上添加更多html内容,请使用div插入正文)
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;
}
现在使用JavaScript将画布调整为全屏显示的大小:
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
可选优化:
就像现在在顶部的小樱桃一样,在< head>< / head>
<!--this is optional-->
<meta name="viewport" content="width=device-width, initial-scale=1">
这篇关于画布未调整为窗口内部宽度&高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!