如何使用JS获取真实的屏幕尺寸(屏幕分辨率)

3

我在想是否存在一种方法可以在 JS 中获取屏幕的实际大小(屏幕分辨率)。

  1. 我知道 screen API,但它的结果不是我想要的。
screen;
// Screen {availWidth: 1680, availHeight: 973, width: 1680, height: 1050, colorDepth: 30, …}

screen.width;
// 1680

screen.height;
// 1050

我得到的是宽度: 1680,高度: 1050;

实际上,屏幕尺寸为2880 x 1800;

我的截图

进入图片描述

进入图片描述

那么,有人可以帮忙吗?


更新苹果Retina屏幕Bug原因 ⚠️

苹果Retina屏幕默认自动缩放至1680px x 1050px

由于无法获取真正的视网膜屏幕大小比例,因此结果不会是2880px x 1800px

但下面的解决方案也是正确的,因为读取的屏幕尺寸为1680px x 1050px,因此结果为3360px x 2100px;

(function getResolution() {
  const realWidth = window.screen.width * window.devicePixelRatio;
  const realHeight = window.screen.height * window.devicePixelRatio;
  console.log(`
    Your screen resolution is: ${realWidth} x ${realHeight}
    Your screen devicePixelRatio is: ${window.devicePixelRatio}
    Your screen width is: ${window.screen.width}
    Your screen height is: ${window.screen.height}
  `);
})();
// Your screen resolution is: 3840 x 2160 (4K)
// Your screen resolution is:  3360 x 2100 ( 3K? Retina Screen)
// Your screen resolution is: 1920 x 1080 ( 1080P / FHD)


enter image description here

refs

https://www.cnblogs.com/xgqfrms/p/14196834.html

https://en.wikipedia.org/wiki/Dots_per_inch

https://en.wikipedia.org/wiki/Display_resolution


显示偏好设置是什么?你是否开启了视网膜缩放? - Richard
@Richard 是的,MBP 2018年版视网膜屏幕,但使用默认显示设置。 - xgqfrms
解决方案:screen.width * window.devicePixelRatioscreen.height * window.devicePixelRatio,获取真实的屏幕分辨率。 - xgqfrms
1个回答

3

屏幕分辨率 ≠ 窗口宽度
大多数操作系统会改变屏幕的dpi,所以screen.width返回的是带有操作系统dpi的屏幕尺寸。例如,我的屏幕分辨率是1920x1080,Windows默认dpi为125,因此js的screen.width返回1600px。

使用以下代码:

function getResolution() {
  const realWidth = window.screen.width * window.devicePixelRatio;
  const realHeight = window.screen.height * window.devicePixelRatio;
  console.log(`Your screen resolution is: ${realWidth} x ${realHeight}`);
}

// test
getResolution();
// Your screen resolution is: 3840 x 2160

enter image description here


不要复制粘贴。您还可以更改文档缩放比例。使用此样式:html {zoom: 0.75} - alborz payande
这种方法在Chrome和FF中的仿真模式下为iPhone8 Plus生成2208x1242。尽管规格说明实际上是1920x1080。然而,对于iPhone 8和iPhone X来说,结果似乎是正确的。 - Dienow
仍然无法推断为什么MacOS视网膜显示器的数字与“screen.width * devicePixelRatio”不同。屏幕分辨率≠窗口宽度,但为什么呢?如果有任何来源就更好了。 - silencej
@silencej,请查看“更新Apple Retina屏幕错误原因⚠️”部分的问题,这可能会帮助您找到原因。 - xgqfrms

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接