我在方形canvas
标记内有一个main
,该标记设置为100vh
高度(和宽度)。我将画布的高度设置为clientHeight
的main
,但是窗口中出现滚动条,指示main
或canvas
(或两者)都高于视口。如果将其设置为clientHeight - 5
,则看不到滚动条。这是为什么?
var cnv = document.getElementsByTagName('canvas')[0];
var main = document.getElementsByTagName('main')[0];
cnv.width = main.clientWidth;
cnv.height = main.clientHeight;
//cnv.width = main.offsetWidth;
//cnv.height = main.offsetHeight;
//cnv.width = main.getBoundingClientRect().width;
//cnv.height = main.getBoundingClientRect().height;
html,body {
margin: 0;
padding: 0;
}
body {
display: flex;
}
main {
background-color: green;
width: 100vh;
height: 100vh;
flex: 0 0 auto;
margin: 0;
padding: 0;
border: 0px solid black;
}
nav {
background-color: #fffdd0;
}
canvas {
background-color: yellow;
margin: 0;
padding: 0;
border: 0px solid black;
}
<main>
<canvas></canvas>
</main>
<nav>Nav with lots of contents, Nav with lots of contents, Nav with lots of contents</nav>
最佳答案
默认情况下,canvas元素的默认显示属性为display: inline;
,因此它位于基线上,该基线从其父对象的底部略微升高以为descenders创建空间。由于画布的高度与其父画布的高度相同,加上底部的基线距离增加,结果是溢出。要解决此问题,只需在画布上添加display: block;
。
var cnv = document.getElementsByTagName('canvas')[0];
var main = document.getElementsByTagName('main')[0];
cnv.width = main.clientWidth;
cnv.height = main.clientHeight;
//cnv.width = main.offsetWidth;
//cnv.height = main.offsetHeight;
//cnv.width = main.getBoundingClientRect().width;
//cnv.height = main.getBoundingClientRect().height;
html,body {
margin: 0;
padding: 0;
}
body {
display: flex;
}
main {
background-color: green;
width: 100vh;
height: 100vh;
flex: 0 0 auto;
margin: 0;
padding: 0;
border: 0px solid black;
}
nav {
background-color: #fffdd0;
}
canvas {
display: block;
background-color: yellow;
margin: 0;
padding: 0;
border: 0px solid black;
display: block;
}
<main>
<canvas></canvas>
</main>
<nav>Nav with lots of contents, Nav with lots of contents, Nav with lots of contents</nav>