簡體   English   中英

為什么出現垂直滾動條時html5 canvas不全屏

[英]why html5 canvas is not full screen when vertical scrollbar appears

我使用全屏 canvas 作為頁面第一部分的背景。 但是當我添加第二部分並出現垂直滾動條時,canvas 的高度會降低一點,並出現間隙。 這是我的代碼:
PS:對不起,我的代碼包含錯誤,我已修復它們。 現在您可以看到紅色間隙。

 var canvas = document.getElementById('canvas') var c = canvas.getContext('2d') scaleCanvas() window.addEventListener("resize", scaleCanvas) function scaleCanvas() { canvas.width = window.innerWidth canvas.height = window.innerHeight c.fillStyle = 'black' c.fillRect(0, 0, canvas.width, canvas.height) }
 * { box-sizing: border-box; max-width: 100%; } body { margin: 0; padding: 0; } #first-section { position: relative; min-height: 100vh; background-color: red; /* to see the gap */ } #content { position: relative; z-index: 2; } #second-section { min-height: 100vh; background-color: blue; } #canvas { display: block; padding: 0; margin: 0; border: none; position: absolute; top: 0; left: 0; z-index: 1; }
 <div id="first-section"> <canvas id="canvas"></canvas> <div id="content">content</div> </div> <div id="second-section"></div>

假設您的意思是全屏,而不是整頁。 兩者非常不同。

如果您的意思是整頁,那么屏幕API 的鏈接也會為您提供有關獲取頁面大小的詳細信息。

尺寸全屏canvas。

問題是您的內容超出了頁面寬度和高度( innerWidthinnerHeight

id first-sectioncontentsecond-section的元素必須在顯示區域內,否則您將獲得滾動條。 滾動條將更改innerWidthinnerHeight值減去滾動條寬度或高度,具體取決於哪個可見。

為了防止滾動條,最好的選擇是將所有內容保留在innerWidthinnerHeight

全屏滾動條。

如果您想要滾動條並且您正在使用全屏,您可以使用屏幕API 來獲取顯示的widthheight (以像素為單位)。 您可以設置 canvas 大小以匹配屏幕,而滾動條不會影響其大小。

注意 請閱讀提供的屏幕鏈接,因為定義屏幕的內容可能與預期不同。 EG 多台顯示器或設備方向會影響您使用 API 的方式。

基本示例

因此,在全屏模式下,您可以設置 canvas 大小並忽略滾動條

function sizeFullScreenCanvas() {
  canvas.width = screen.width;
  canvas.height= screen.height;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM