How to get real PPI (pixels per inch) device resolution with javascript?
some examples of device and value expected:
Dividing the physical ppi by the ideal ppi of 150, gives the device pixel ratio.
The devicePixelRatio of Window interface returns the ratio of the resolution in physical pixels to the resolution in CSS pixels for the current display device. This value could also be interpreted as the ratio of pixel sizes: the size of one CSS pixel to the size of one physical pixel.
In the world of web development, the device pixel ratio (also called CSS Pixel Ratio and also referred to as dppx) is what determines how a device's screen resolution is interpreted by the CSS.
DPI refers to the number of printed dots contained within one inch of an image printed by a printer. PPI refers to the number of pixels contained within one inch of an image displayed on a computer monitor.
Running a native application directly on top of the operating system is the only surefire way to acquire the physical characteristics of the client monitor stored in the EDID. No mainstream browser engine currently offers this information through any web API and will likely not in the foreseeable future. However there are several ways to approximate the density to varying levels of accuracy.
All modern browsers give hints to the pixel density via attributes like devicePixelRatio, deviceXDPI which basically tell you how much zoom the client has going on (versus 1.0x Operating System default zoom). If you're targeting only a few devices like the Apple line then you might be able to tell which one is which, although Apple doesn't leave a scrap of a clue to discern a iPad mini from a regular iPad.
Another alternative is using device databases or proprietary software that analyze the client's "user agent string" to achieve a hit-or-miss guess of the device and then looking up the DPI associated with that device if it exists in their big database. Expensive proprietary systems might have higher accuracy by leveraging complex data mining algorithms but regardless any system like this would need constant manual updating and will still remain open to client manipulation since they can just change their user agent string ("view this website in desktop mode")
It's really an unfortunate situation not having this information available. I've spent countless hours researching ANY POSSIBLE WAY to make a PPI aware Web Application.
Maybe one day someone will be able to convince the folks at WebKit or Mozilla or Microsoft to allow people to create PPI aware Web apps for augmented reality and such... Sigh
In pure JS:
function calcScreenDPI() {
const el = document.createElement('div');
el.style = 'width: 1in;'
document.body.appendChild(el);
const dpi = el.offsetWidth;
document.body.removeChild(el);
return dpi;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With