我正在尝试创建一个画布元素,该元素占用视口宽度和高度的100%。
您可以在我的示例中看到这种情况的发生,但是它正在Chrome和FireFox中添加滚动条。如何防止多余的滚动条,仅将窗口的宽度和高度精确设置为画布的大小?
为了始终使画布全屏显示宽度和高度,这意味着即使调整了浏览器的大小,也需要在将画布调整为window.innerHeight和window.innerWidth的函数中运行绘制循环。
HTML
<canvas id="canvas"></canvas>
JavaScript
(function() { var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'); // resize the canvas to fill browser window dynamically window.addEventListener('resize', resizeCanvas, false); function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; /** * Your drawings need to be inside this function otherwise they will be reset when * you resize the browser window and the canvas goes will be cleared. */ drawStuff(); } resizeCanvas(); function drawStuff() { // do your drawing stuff here } })();
CSS
* { margin:0; padding:0; } /* to remove the top and left whitespace */ html, body { width:100%; height:100%; } /* just to be sure these are full screen*/ canvas { display:block; } /* To remove the scrollbars */
这样可以正确地使画布达到浏览器的整个宽度和高度。您只需要在drawStuff()函数中将所有用于绘制的代码放到画布上即可。