我正在开发一种独特的应用程序,它需要根据显示图像的设备来生成特定分辨率的图像。因此,在普通的Windows浏览器(96ppi)、iPhone (163ppi)、安卓G1 (180ppi)和其他设备上,输出是不同的。我想知道有没有办法自动检测出来。
我最初的研究似乎是否定的。我看到的唯一建议是在CSS中创建一个宽度指定为"1in“的元素,然后检查它的offsetWidth (另请参阅How to access screen display’s DPI settings via javascript?)。有道理,但iPhone用这种技术对我撒谎,说它是96ppi。
另一种方法可能是以英寸为单位获得显示器的尺寸,然后除以以像素为单位的宽度,但我也不确定如何做到这一点。
发布于 2014-09-24 05:17:25
<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
var devicePixelRatio = window.devicePixelRatio || 1;
dpi_x = document.getElementById('testdiv').offsetWidth * devicePixelRatio;
dpi_y = document.getElementById('testdiv').offsetHeight * devicePixelRatio;
console.log(dpi_x, dpi_y);
</script>
从这里抓起的http://www.infobyip.com/detectmonitordpi.php。在移动设备上工作!(android 4.2.2测试)
发布于 2016-03-11 21:37:35
我想出了一种不需要DOM的方法。完全没有
DOM可能很混乱,要求您在不知道样式表中的width: x !important发生什么情况的情况下将内容附加到正文中。您还必须等待DOM准备好使用...
/**
* Binary search for a max value without knowing the exact value, only that it can be under or over
* It dose not test every number but instead looks for 1,2,4,8,16,32,64,128,96,95 to figure out that
* you thought about #96 from 0-infinity
*
* @example findFirstPositive(x => matchMedia(`(max-resolution: ${x}dpi)`).matches)
* @author Jimmy Wärting
* @see {@link https://stackoverflow.com/a/35941703/1008999}
* @param {function} fn The function to run the test on (should return truthy or falsy values)
* @param {number} start=1 Where to start looking from
* @param {function} _ (private)
* @returns {number} Intenger
*/
function findFirstPositive (f,b=1,d=(e,g,c)=>g<e?-1:0<f(c=e+g>>>1)?c==e||0>=f(c-1)?c:d(e,c-1):d(c+1,g)) {
for (;0>=f(b);b<<=1);return d(b>>>1,b)|0
}
var dpi = findFirstPositive(x => matchMedia(`(max-resolution: ${x}dpi)`).matches)
console.log(dpi)
发布于 2011-11-21 22:01:33
有一个resolution CSS media查询-它允许你将CSS样式限制到特定的分辨率:
然而,it’s only supported by Firefox 3.5 and above, Opera 9 and above, and IE 9。其他浏览器根本不会应用您的分辨率特定样式(尽管我没有检查过非桌面浏览器)。
https://stackoverflow.com/questions/279749
复制相似问题