You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多屏场景下screen.width与screen.height返回错误屏幕分辨率如何解决?

问题解答

关于是否为浏览器有意设计

这是浏览器的标准设计,原因主要有两点:

  • 历史兼容性:screen API 诞生时Web生态几乎没有多显示器使用场景,规范默认定义screen.width/screen.height返回的是主屏幕的分辨率参数,该行为延续至今没有做破坏性变更。
  • 隐私安全限制:随意获取用户所有外接屏幕的参数会增加浏览器用户被设备指纹追踪的风险,因此默认情况下浏览器不会暴露非主屏幕的分辨率参数。

可行的修复方案

  • 若仅需要浏览器窗口内的全屏Canvas,直接替换取值逻辑即可:放弃使用screen相关属性,改用window.innerWidth和window.innerHeight,这两个属性始终返回当前浏览器窗口实际的宽高值,不受主屏幕参数影响,搭配devicePixelRatio调整画布清晰度即可:
const canvas = document.querySelector('canvas');
const dpr = window.devicePixelRatio || 1;
// 设置画布实际像素尺寸
canvas.width = window.innerWidth * dpr;
canvas.height = window.innerHeight * dpr;
// 设置画布页面显示尺寸
canvas.style.width = `${window.innerWidth}px`;
canvas.style.height = `${window.innerHeight}px`;
  • 若需要系统级全屏下的Canvas,在调用全屏API触发fullscreenchange事件后再读取尺寸即可:
async function setFullscreenCanvas() {
  const canvas = document.querySelector('canvas');
  const dpr = window.devicePixelRatio || 1;
  // 触发系统全屏
  await document.documentElement.requestFullscreen();
  // 读取全屏状态下的视口尺寸
  canvas.width = window.innerWidth * dpr;
  canvas.height = window.innerHeight * dpr;
  canvas.style.width = `${window.innerWidth}px`;
  canvas.style.height = `${window.innerHeight}px`;
}
  • 如果确实需要获取当前窗口所在屏幕的完整物理分辨率,可以使用新版多屏Web API,该API需要用户授权,仅在HTTPS/localhost环境下可用。

内容的提问来源于stack exchange,提问作者Norse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 11:45:04