0

I've tried various ways of determining the size of the browser's client area in terms of physical pixels, but I get a non-integer result on mobile devices.

For example: window.outerWidth * window.devicePixelRatio on a Pixel 2 with Chrome yields 1081.5 even though I know that the browser's client area is actually 1080 pixels wide.

Another way of seeing this is going to mydevice.io and multiplying JS screen.width with JS pixel-ratio.

Is there a better way to determine physical client size?

prideout
  • 2,895
  • 1
  • 23
  • 25
  • 1
    Check: https://stackoverflow.com/questions/21680629/getting-the-physical-screen-dimensions-dpi-pixel-density-in-chrome-on-androi –  Sep 11 '18 at 22:51
  • Nice find! The predominant answer in that question is "do not do that" but I want to draw pixel-perfect text in WebGL, and I'd like to set up a correct framebuffer size for doing this in my canvas element. – prideout Sep 11 '18 at 22:58

3 Answers3

3

ResizeObserver and or devicePixelContentBox can be used for this, at least on some browsers.

More information is available in the following article:

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

prideout
  • 2,895
  • 1
  • 23
  • 25
  • 1
    for reference here's a few threads: https://www.khronos.org/webgl/public-mailing-list/public_webgl/1406/msg00019.php, https://github.com/KhronosGroup/WebGL/issues/2460 – gman Sep 12 '18 at 09:33
  • Cool that someone is solving this problem, but wouldn't more accurate `devicePixelRatio` suffice as a solution? – HankMoody Sep 12 '18 at 17:43
  • 1
    It doesn't sound like any higher res devicePixelRatio would help. It looks like every layout engine does different things to decide exactly how many pixels to make something whether they use floor or ceil or round and when they use them in what order with what other options (borders, padding, margins, etc...) such that there is no simple answer. – gman Sep 13 '18 at 06:33
-2
<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>
Mohit
  • 776
  • 7
  • 13
-2

If you want to exclude client taskbars, you can use window.screen.availHeight and window.screen.availWidth.

Else, use window.screen.height and window.screen.width.

Source

Bonlou
  • 472
  • 2
  • 9
  • `window.screen.width` and `window.screen.availWidth` both return CSS pixels. My question is about physical pixels. – prideout Sep 11 '18 at 22:48
  • My bad, I didn't understand that, and I don't even know the difference. Good luck – Bonlou Sep 11 '18 at 23:00