gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:49:35 30 4
gpt4 key购买 nike

我正在尝试创建一个占据视口(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/37419823/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com