jquery - HTML5 Canvas 100% 视口(viewport)宽度高度?

标签 jquery html canvas viewport

我正在尝试创建一个占据视口(viewport) 100% 宽度和高度的 Canvas 元素。

你可以在我的例子中看到here这种情况正在发生,但是它在 Chrome 和 FireFox 中都添加了滚动条。我怎样才能防止额外的滚动条,并且只提供窗口的宽度和高度正好是 Canvas 的大小?

最佳答案

为了使 Canvas 始终全屏显示宽度和高度,这意味着即使在调整浏览器大小时,您也需要在将 Canvas 大小调整为 window.innerHeightwindow.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 */

这就是您如何正确地使 Canvas 成为浏览器的全宽和全高。您只需将所有绘制到 Canvas 的代码放在 drawStuff() 函数中。

关于jquery - HTML5 Canvas 100% 视口(viewport)宽度高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56417238/

相关文章:

javascript - 通过鼠标拖动创建多边形形状不会使形状以其选择边框框为中心

Javascript 上下文菜单点击事件/检测 - 过滤粘贴内容

php - 查询 functions.php 中的函数?

javascript - Protovis Jquery 工具提示问题

html - 列表项对齐

javascript - 无法向 DOM 添加元素

javascript - 用户可以更改 javascript 闭包函数吗?

javascript - Opera 中 document.onload 事件中插件的事件监听器

html - 电子邮件中的同一页面链接

javascript - draw2d javascript 库 - 多行标签