正如@Alex 所说,您可以使用该getComputedStyle
函数获取画布的当前大小。
但是...要使画布始终全屏宽度和高度,这意味着即使调整浏览器大小,您也需要在将画布大小调整为window.innerHeight
and的函数中运行绘制循环window.innerWidth
。
一旦你这样做了,你就可以使用 normalcanvas.height
和canvas.width
函数来获得正确的画布大小:
(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
* to avoid canvas to be cleared. */
drawStuff();
}
resizeCanvas();
function drawStuff() {
console.log(canvas.height); //925
console.log(canvas.width); //1627
// do your drawing stuff here
}
})();
另外:使用这个 CSS hacks 使画布全尺寸没有问题:
/* remove the top and left whitespace */
* { margin:0; padding:0; }
/* just to be sure these are full screen*/
html, body { width:100%; height:100%; }
/* To remove the scrollbar */
canvas { display:block; }