HTML5画布自适应窗口大小

11

我正在尝试让我的画布适应页面大小,当我这样做时:

ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

它在水平和垂直方向上刚好超出了滚动条的大小,因此会添加滚动条。 它超出的大小大约是在滚动条出现之前就被计算在内的(只是一个猜测),这是否是正在发生的事情?如何使其适合页面而没有滚动条?


1
为什么不使用CSS禁用滚动条呢?html,body {overflow:hidden;} - net.uk.sweet
谢谢,应该想到了,现在只能这样做了 :) - Larry
请参考此处的示例:http://bravenewmethod.wordpress.com/2011/08/28/html5-canvas-layout-and-mobile-devices/。 - Teemu Ikonen
4个回答

16

将画布位置设置为absolute。另外,请确保包含元素中没有设置填充或边距。

这是我在所有全屏画布演示中使用的方法。

body, html {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
}
canvas {
    position:absolute;
}

全屏演示


1
喜欢它。非常感谢你。 - DollarAkshay
画布 { 宽度:100%; 高度:100%; } 这也可以工作,而且最好不要使用绝对定位。(例如,如果您使用绝对定位并且画布大于页面,则无法向上或向下移动)。 - Fed

2

默认情况下,画布被设置为 display: inline-block。将其更改为 display: block

body {
    margin: 0;
    padding: 0;
}
canvas {
    display: block;
}

这对我没用。(Chrome 版本 57.0.2987.133(64 位)) - keithpjolley

1
这对我有用。
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);

0

我曾经遇到过同样的问题,我通过去掉 border 来解决它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接