对于全屏 canvas,如何确定浏览器客户端大小?

For a full-screen canvas, how do I determine browser client size?

我尝试了多种方法来确定浏览器客户区的物理像素大小,但我在移动设备上得到的结果不是整数。

例如:window.outerWidth * window.devicePixelRatio 在具有 Chrome 的 Pixel 2 上产生 1081.5,即使我知道浏览器的客户区实际上是 1080 像素宽。

另一种理解方式是 mydevice.io 并将 JS screen.widthJS pixel-ratio 相乘。

是否有更好的方法来确定物理客户规模?

<button onclick="myFunction()">Try it</button>

    <p><strong>Note:</strong> The innerWidth and innerHeight properties are not supported in IE8 and earlier.</p>

    <p id="demo"></p>

    <script>
    function myFunction() {
        var w = window.innerWidth;
        var h = window.innerHeight;
        document.getElementById("demo").innerHTML = "Width: " + w + "<br>Height: " + h;
    }
    </script>

如果要排除客户端任务栏,可以使用 window.screen.availHeightwindow.screen.availWidth

否则,使用 window.screen.heightwindow.screen.width

Source

ResizeObserver 和/或 devicePixelContentBox 可用于此目的,至少在某些浏览器上是这样。

更多信息可在以下文章中找到:

https://web.dev/device-pixel-content-box/