Unity WebGL 游戏保持宽高比的完整解决方案

2次阅读

Unity WebGL 游戏保持宽高比的完整解决方案

本文详解如何通过 javascript 动态控制 unity webgl 容器尺寸,强制维持指定宽高比(如 16:9),避免浏览器窗口缩放导致画面拉伸或变形,无需修改 unity 项目代码,仅需调整发布后的 index.html。

本文详解如何通过 javascript 动态控制 unity webgl 容器尺寸,强制维持指定宽高比(如 16:9),避免浏览器窗口缩放导致画面拉伸或变形,无需修改 unity 项目代码,仅需调整发布后的 index.html。

在 Unity 构建 WebGL 平台时,生成的默认 HTML 页面会将游戏容器(通常为 #unity-container)设为自适应布局,但其默认行为不保证宽高比约束——当用户缩放浏览器窗口或在不同设备上访问时,canvas 可能被强行拉伸,造成 ui 错位、角色变形、UI 元素挤压等严重视觉问题。

根本原因在于:CSS 的 min-width/min-height 或 vw/vh 单位无法实现「等比缩放」逻辑;它们只能设定最小尺寸或视口百分比,而无法动态计算并维持一个固定宽高比(如 16:9、4:3 或 1:1)。真正的解决方案是通过 JavaScript 实时计算最优尺寸,并主动设置容器宽高

✅ 推荐实现:响应式等比缩放脚本

将以下脚本插入 Unity 导出的 index.html 文件中

底部(位于 unityFramework.js 加载之后、 之前):

<script> function resizeGame() {   const gameContainer = document.getElementById("unity-container");   if (!gameContainer) return;    // 设置目标宽高比(例如 16:9 → 16/9 ≈ 1.777...)   const targetRatio = 16 / 9;   const viewportWidth = window.innerWidth;   const viewportHeight = window.innerHeight;   const currentRatio = viewportWidth / viewportHeight;    let newWidth, newHeight;    // 保持容器完全可见且不溢出视口,同时严格维持 targetRatio   if (currentRatio > targetRatio) {     // 视口过宽(如横屏大显示器)→ 以高度为基准,宽度按比例缩放     newHeight = viewportHeight;     newWidth = viewportHeight * targetRatio;   } else {     // 视口过高(如竖屏或窄窗口)→ 以宽度为基准,高度按比例缩放     newWidth = viewportWidth;     newHeight = viewportWidth / targetRatio;   }    // 应用计算后的尺寸(单位:px)   gameContainer.style.width = math.round(newWidth) + 'px';   gameContainer.style.height = Math.round(newHeight) + 'px'; }  // 首次加载即执行,确保初始尺寸正确 resizeGame();  // 监听窗口大小变化,实时响应 window.addEventListener('resize', resizeGame, { passive: true }); </script>

? 关键说明与最佳实践

  • 容器选择必须准确:确保 getElementById(“unity-container”) 中的 ID 与实际 HTML 中一致。Unity 2021.3+ 默认使用 #unity-container;若你自定义了容器 ID(如 #my-game),请同步修改。
  • CSS 配合建议:为避免布局抖动,建议在 style.css 中补充以下样式:
    #unity-container {   margin: 0 auto; /* 水平居中 */   display: flex;   justify-content: center;   align-items: center; } body, html {   margin: 0;   padding: 0;   overflow: hidden; /* 防止因尺寸计算误差导致滚动条 */ }
  • 性能优化:使用 { passive: true } 注册 resize 事件,提升滚动/缩放流畅度;Math.round() 避免小数像素引起的渲染模糊。
  • 扩展性提示:如需适配移动端竖屏(如 9:16),可检测 window.orientation 或 screen.availHeight > screen.availWidth 后动态切换 targetRatio。

⚠️ 常见误区提醒

  • ❌ 不要仅依赖 CSS(如 aspect-ratio):该属性在部分旧版浏览器(如 safari
  • ❌ 不要修改 #unity-canvas 的宽高:Unity 运行时会覆盖其 style.width/height,应始终操作外层容器(#unity-container)。
  • ❌ 避免在 window.onload 中延迟执行 resizeGame():可能导致首帧渲染错位;直接调用一次更可靠。

通过上述方案,你的 Unity WebGL 游戏将在任意分辨率、任意设备上稳定呈现原始设计比例,兼顾视觉一致性与用户体验。此方法轻量、兼容性强(支持 IE11+),且无需改动 Unity 工程设置或 C# 代码,是生产环境推荐的标准实践。

text=ZqhQzanResources