小编典典

HTML5 Canvas 100% 宽度视口高度?

all

我正在尝试创建一个占视口宽度和高度 100% 的画布元素。

您可以在我的示例中看到这种情况正在发生,但是它在 Chrome 和 FireFox
中都添加了滚动条。我怎样才能防止额外的滚动条,只提供窗口的宽度和高度作为画布的大小?


阅读 190

收藏
2022-08-08

共1个答案

小编典典

为了使画布始终全屏宽度和高度,这意味着即使调整浏览器大小,您也需要在将画布大小调整为window.innerHeightand的函数中运行绘制循环window.innerWidth

示例:http:
//jsfiddle.net/jaredwilli/qFuDr/

HTML

<canvas id="canvas"></canvas>

JavaScript

(function() {
  const canvas = document.getElementById('canvas');
  const 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()函数中的画布即可。

2022-08-08