gpt4 book ai didi

javascript - Canvas 变得比容器大,而两者的大小应该完全相同

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:17 31 4
gpt4 key购买 nike

我在方形 main 标签内有一个 canvas,它设置为 100vh 高度(和宽度)。我将 Canvas 的高度设置为 mainclientHeight,但我在窗口中得到了一个滚动条,表明 maincanvas(或两者)比视口(viewport)高。如果我将它设置为 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 创造空间。 .由于 Canvas 与其父级的高度相同加上底部添加的基线间距,结果是溢出。要解决此问题,只需将 display: block; 添加到您的 Canvas 即可。

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>

关于javascript - Canvas 变得比容器大,而两者的大小应该完全相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57775613/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com