我正在尝试让我的画布适应页面大小,当我这样做时:
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
它在水平和垂直方向上刚好超出了滚动条的大小,因此会添加滚动条。 它超出的大小大约是在滚动条出现之前就被计算在内的(只是一个猜测),这是否是正在发生的事情?如何使其适合页面而没有滚动条?
我正在尝试让我的画布适应页面大小,当我这样做时:
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
它在水平和垂直方向上刚好超出了滚动条的大小,因此会添加滚动条。 它超出的大小大约是在滚动条出现之前就被计算在内的(只是一个猜测),这是否是正在发生的事情?如何使其适合页面而没有滚动条?
将画布位置设置为absolute
。另外,请确保包含元素中没有设置填充或边距。
这是我在所有全屏画布演示中使用的方法。
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
position:absolute;
}
默认情况下,画布被设置为 display: inline-block
。将其更改为 display: block
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
function resize() {
var canvas = document.getElementById('game');
var canvasRatio = canvas.height / canvas.width;
var windowRatio = window.innerHeight / window.innerWidth;
var width;
var height;
if (windowRatio < canvasRatio) {
height = window.innerHeight;
width = height / canvasRatio;
} else {
width = window.innerWidth;
height = width * canvasRatio;
}
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
};
window.addEventListener('resize', resize, false);
我曾经遇到过同样的问题,我通过去掉 border
来解决它。