小编典典
为了始终使画布全屏显示宽度和高度,这意味着即使调整了浏览器的大小,也需要在将画布调整为window.innerHeight和window.innerWidth的函数中运行绘制循环。
HTML
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()函数中将所有用于绘制的代码放到画布上即可。
2020-05-10