Find screen sizes in inches, not pixels, using javascript

I read a lot of questions about SO about the best ways to determine the screen size in pixels, which ultimately depends on the resolution in order to find the actual screen size.

I know that some mobile devices have a small screen (say 4 inches), but the resolution is high. Although some r devices have a large screen (e.g. 7inch tab), the resolution is low.

Therefore, when you want to display your page to the user, you really need a screen size in centimeters or centimeters to provide the best view soothing your eyes.

So, I ask: Was it possible to find out the screen size of the device in inches, not pixels? I know that this is possible if we know the resolution !! Bec we can calculate the size of the width and height of the screen

Appreciate any idea!

+4
source share
3 answers

Once you get the screen resolution in pixels, you can work with dpi resolution with a hidden div:

<div id="dpi" style="height: 1in; width: 1in; left: 100%; position: fixed; top: 100%;"></div>

Js

var dpi_x = document.getElementById('dpi').offsetWidth;
var dpi_y = document.getElementById('dpi').offsetHeight;

then do the resolution in inches:

var width = screen.width / dpi_x;
var height = screen.height / dpi_y;

Example

+13
source

Now, as far as I can tell, there is no reliable way to accurately get the width of the device’s screen. Everything (including inches, 1in == 96px) is based one way or another on screen resolution.

, , , , . , , - , .

, ,

if (screen.height <= 768)

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent))

, , , , .

: fooobar.com/questions/89891/...

+1

"width: 1in". div. . 1 (Windows 7), (LG G4). : Chrome 64.0.3282.140 FireFox 58.0.1.

On my phone, the div size is about 11/16 inches in both browsers. On my desktop, the div is slightly less than 17/16 inches in both browsers.

Perhaps better than wild guesses, but not many.

Test file:

<!doctype html>

<html>
<style>
-ms-@viewport {
    width: device-width;
    initial-scale: 1;
    zoom: 1;
}
@viewport {
    width: device-width;
    initial-scale: 1;
    zoom: 1;
}
</style>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test DPI</title>
</head>
<body style="margin: .5cm">
<h1 class=title>Test DPI 2</h1>

<div style="width: 1in; height: 1cm;background-color:black"></div>


</body>
</html>
Run code
0
source

Source: https://habr.com/ru/post/1540207/


All Articles