HTML5 Canvas 100% 宽视口的高度? [英] HTML5 Canvas 100% Width Height of Viewport?

查看:21
本文介绍了HTML5 Canvas 100% 宽视口的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a canvas element that takes up 100% of the width and height of the viewport.

您可以在我的示例此处中看到正在发生的情况,但是它在 Chrome 和 FireFox 中都添加了滚动条.如何防止出现额外的滚动条,并仅提供窗口的宽度和高度作为画布的大小?

You can see in my example here that is occurring, however it is adding scroll bars in both Chrome and FireFox. How can I prevent the extra scroll bars and just provide exactly the width and height of the window to be the size of the canvas?

推荐答案

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

In order to make the canvas full-screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.

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

<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() 函数中将所有用于绘制的代码放到画布上.

That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.

这篇关于HTML5 Canvas 100% 宽视口的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆