简体   繁体   中英

why html5 canvas is not full screen when vertical scrollbar appears

I'm using a full screen canvas as background of the first section of my page. But as soon as I add the second section and vertical scrollbar appears, the height of canvas reduces a little bit and a gap appears. here's my code:
PS: Sorry, my code contained bugs, I fixed them. now you can see the red gap.

 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>

Assuming you mean full screen, and not full page. The two are very different.

If you mean full page then the link to the Screen API will also give you details on obtaining the page size.

Size full screen canvas.

The problem is that you have content that extends outside the page width and height ( innerWidth , innerHeight )

The elements with ids first-section , content , and second-section must be inside the display area or else you will get a scroll bar. The scroll bar will change the innerWidth , innerHeight values subtracting the scrollbar width or height depending on which is visible.

To prevent scroll bars the best option is to keep all content inside innerWidth , and innerHeight

Full screen with scroll bars.

If you want have the scroll bars and you are using full screen you can use the Screen API to get the width and height of the display in pixels. You can set the canvas size to match the screen without the scroll bars effecting its size.

Note Do read the provided link to Screen as what defines the screen may not be as expected. EG more than one monitor, or device orientation will effect how you use the API.

Basic example

Thus when in full-screen mode you can set the canvas size and ignore scroll bars with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM