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

Unity WebGL游戏如何保持分辨率比例,避免窗口缩放变形?

解决Unity WebGL游戏浏览器窗口缩放时画面变形问题

要让Unity WebGL游戏在浏览器窗口调整时保持原始比例,核心是固定游戏容器的宽高比,再让Canvas在容器内自适应填充——你之前用的min-width/min-height只是设置元素最小尺寸,无法约束比例,所以没效果。

具体实现步骤

1. 调整CSS样式

假设你的HTML结构是Unity WebGL导出的标准结构(包含#unity-container和#unity-canvas),替换style.css内容为以下代码:

/* 重置页面默认边距与滚动行为 */
html, body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #000; /* 可选:用黑色填充比例不符的空白区域 */
}

/* 固定游戏容器的宽高比 */
#unity-container {
  /* 替换为你的游戏原始宽高比,比如16:9写16/9,4:3写4/3 */
  aspect-ratio: 16/9;
  width: 100%;
  max-width: 1920px; /* 可选:限制最大宽度,避免超大窗口下画面模糊 */
  max-height: 1080px; /* 可选:限制最大高度 */
  position: relative;
}

/* 让Canvas自适应容器,严格保持比例 */
#unity-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain; /* 关键:完整显示画面,比例不符时留黑边 */
  /* 若想裁剪超出部分(不留黑边但裁掉边缘内容),改为 object-fit: cover; */
}

2. 兼容旧浏览器(可选)

如果需要兼容不支持aspect-ratio的旧浏览器,用padding-top比例法替换容器的aspect-ratio属性:

#unity-container {
  width: 100%;
  max-width: 1920px;
  position: relative;
  /* 16:9比例对应 padding-top: 56.25%(9/16*100%),4:3对应75% */
  padding-top: 56.25%;
}

3. Unity编辑器内的配套设置

打开Unity的Player Settings(Edit > Project Settings > Player),切换到WebGL平台:

  • 在Resolution and Presentation中,设置Default Screen Width和Default Screen Height为游戏原始分辨率(比如1920x1080)
  • 确保Render Mode选择Canvas(或对应WebGL版本),并勾选Resize with browser window,让Unity根据容器尺寸自动调整渲染分辨率。

原理说明

  • 固定容器宽高比后,无论窗口如何缩放,容器都会维持你设置的比例
  • object-fit: contain 让Canvas在容器内完整显示,自动适配尺寸的同时保持原始比例,不会拉伸变形
  • 外层flex布局让游戏容器始终居中,提升视觉体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:08:10