Home > Article > Web Front-end > How to Accurately Detect DPI/PPI from JS/CSS in the Face of Device Deception?
Maintaining a consistent user experience across devices with varying DPI/PPI settings is crucial for modern applications that generate high-resolution images. However, accurately detecting the device's DPI/PPI presents challenges, as traditional methods may not provide reliable results.
Your initial approach using an element with a fixed "1in" width in CSS and checking its offsetWidth seems reasonable. However, iPhone has been known to misreport its PPI, giving a false value of 96ppi. This false reading renders this method unreliable.
Another potential solution is to retrieve the device display dimensions in inches and divide them by the width in pixels. However, accessing these dimensions is not straightforward in JS/CSS.
Fortunately, there is a reliable method to obtain the device DPI/PPI:
<code class="javascript">const testDiv = document.createElement('div'); testDiv.style.height = '1in'; testDiv.style.left = '-100%'; testDiv.style.position = 'absolute'; testDiv.style.top = '-100%'; testDiv.style.width = '1in'; document.body.appendChild(testDiv); const DPI_X = testDiv.offsetWidth * window.devicePixelRatio; const DPI_Y = testDiv.offsetHeight * window.devicePixelRatio; console.log(DPI_X, DPI_Y);</code>
This method provides accurate DPI/PPI readings on various devices, including those that may misreport their PPI using traditional methods.
The above is the detailed content of How to Accurately Detect DPI/PPI from JS/CSS in the Face of Device Deception?. For more information, please follow other related articles on the PHP Chinese website!