Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the screen DPI using JavaScript

The only way I found till now, is getting the offsetWidth, offsetHeight of a test div element with height and width of one inch: http://www.infobyip.com/detectmonitordpi.php

Is there a way to detect the screen DPI via JavaScript instead?

Thanks,

Atara.

like image 838
Atara Avatar asked Feb 15 '12 11:02

Atara


People also ask

How do I get PPI in Javascript?

js: screenPPI = document. getElementById('ppitest'). offsetWidth; This got me 96, which corresponds to my system's ppi.

How do I know my PPI DPI?

If you know the PPI – again, let's say 300 – you divide the total dimensional pixels to determine the inches: 1920/300 = 6.4. 1080/300 = 3.6.


3 Answers

In webkit you can detect if your user has a so called "high dpi screen" by simply retrieving the value from:

window.devicePixelRatio

Normal dpi screens will return 1. The iPhone 4 will return 2, but numbers like 1.8 or 2.12 are also possible.

like image 153
laurens peeters Avatar answered Oct 05 '22 21:10

laurens peeters


<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
    dpi_x = document.getElementById('testdiv').offsetWidth;
    dpi_y = document.getElementById('testdiv').offsetHeight;
</script>

Then you can use JQuery to send dpi_x and dpi_y this to to your server

http://jsfiddle.net/sxfv3/

like image 24
Lixas Avatar answered Oct 05 '22 22:10

Lixas


There is, so far, no standard and supported-everywhere solution.

window.devicePixelRatio, as suggested by laurens peeters, does work if you don't care about IE, or any browser from the ancient times, like early January 2013 (e.g., Firefox 17).

See Cross Browser Retina/High Resolution Media Queries (and various comments and links there) for how to get this information as of late 2012, but you'll have to keep searching again, and adjusting your code, every so often until something finally gets standardized, and implemented in every browser, with widespread-enough version adoption that you can stop caring about older versions…

like image 42
abarnert Avatar answered Oct 05 '22 21:10

abarnert