写个方法获取屏幕的DPI
function getDPI() {
// 创建一个隐藏的div元素
const div = document.createElement('div');
div.style.width = '1in';
div.style.height = '1in';
div.style.position = 'absolute';
div.style.left = '-100%';
div.style.top = '-100%';
document.body.appendChild(div);
// 获取div的像素宽度和高度
const widthPx = div.offsetWidth;
const heightPx = div.offsetHeight;
// 移除div元素
document.body.removeChild(div);
// 计算DPI
const dpi = Math.round(widthPx); // 宽度和高度应该相同,选择一个即可
return dpi;
}
// 示例用法:
const dpi = getDPI();
console.log(`Screen DPI: ${dpi}`);
// 更健壮的方法 (考虑dppx)
function getDevicePixelRatio() {
let ratio = 1;
// To account for zoom, change to use deviceXDPI instead of systemXDPI
if (window.screen.systemXDPI !== undefined && window.screen.systemYDPI !== undefined && window.screen.systemXDPI > window.screen.systemYDPI) {
ratio = window.screen.systemXDPI / window.screen.logicalXDPI;
}
else if (window.devicePixelRatio !== undefined) {
ratio = window.devicePixelRatio;
}
return ratio;
}
function getDPI2() {
const inchElem = document.createElement('div');
inchElem.style.width = '1in';
inchElem.style.height = '1in';
inchElem.style.position = 'fixed'; // or 'absolute'
inchElem.style.left = '0';
inchElem.style.top = '0';
inchElem.style.visibility = 'hidden'; // to avoid any potential layout interference.
document.body.appendChild(inchElem);
const devicePixelRatio = getDevicePixelRatio();
const dpi = Math.round(inchElem.offsetWidth * devicePixelRatio);
document.body.removeChild(inchElem);
return dpi;
}
const dpi2 = getDPI2();
console.log(`Screen DPI (more robust): ${dpi2}`);
代码解释:
-
创建一个隐藏的div: 创建一个
div
元素,并将其设置为1in
宽和高。position: absolute; left: -100%; top: -100%;
确保它不影响页面布局,并且不可见。 -
获取像素尺寸: 使用
offsetWidth
和offsetHeight
获取div
的像素宽度和高度。由于div
设置为1in
,这些值将代表屏幕上每英寸的像素数。 -
移除div: 从文档中移除临时创建的
div
。 -
计算DPI: 返回
offsetWidth
的值,它代表屏幕的DPI。 (高度也一样)
更健壮的方法的解释:
getDPI2()
和 getDevicePixelRatio()
的组合提供了更可靠的结果,尤其是在高分辨率屏幕和缩放情况下。
getDevicePixelRatio()
: 考虑了设备像素比 (dppx),它表示物理像素与逻辑像素的比率。在视网膜屏幕和其他高分辨率显示器上,此值大于 1。getDPI2()
: 类似于getDPI()
,但它使用getDevicePixelRatio()
来调整计算,从而提供更准确的 DPI 值。 另外使用了visibility: hidden
避免潜在的布局干扰,并且使用fixed
或absolute
定位。
重要注意事项:
- 近似值: 这种方法提供的是DPI的近似值,因为浏览器可能会对
1in
的解释略有不同。 - 缩放: 用户缩放浏览器可能会影响结果。
getDPI2()
结合getDevicePixelRatio()
能够更好地处理缩放问题,但仍然可能存在一些差异。 - 操作系统缩放: 操作系统级别的缩放设置也会影响结果。 更健壮的方法尝试解决这个问题,但仍然可能不完美。
希望这些代码片段能够帮助你获取屏幕的DPI。 建议使用更健壮的方法 getDPI2()
以获得更准确的结果。