
本文介绍通过 javascript 动态计算并设置 unity webgl 容器尺寸的方法,确保游戏始终按指定宽高比(如 16:9)居中缩放显示,避免浏览器窗口调整导致的画面拉伸或裁切。
本文介绍通过 javascript 动态计算并设置 unity webgl 容器尺寸的方法,确保游戏始终按指定宽高比(如 16:9)居中缩放显示,避免浏览器窗口调整导致的画面拉伸或裁切。
在 Unity 构建 WebGL 项目时,生成的默认 index.html 会将游戏 Canvas 嵌入一个容器(通常为
解决的关键在于放弃纯 CSS 的“填满式”布局(如 100vw/100vh),转而采用 JavaScript 主动控制容器尺寸:根据当前浏览器窗口宽高,按目标宽高比(如 16:9)动态计算出最大可用尺寸,并将容器设为该尺寸,同时配合 CSS 居中与 overflow: hidden 实现安全适配。
✅ 正确实现方案
将以下脚本插入 index.html 的
底部(推荐在 Unity 生成的 <script> 标签之后):<pre class="brush:php;toolbar:false;"><script> function resizeGame() { const gameContainer = document.getElementById("unity-container"); if (!gameContainer) return; // 设置目标宽高比(例如 16:9) const targetRatio = 16 / 9; const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; const windowRatio = windowWidth / windowHeight; let newWidth, newHeight; if (windowRatio > targetRatio) { // 窗口更宽 → 以高度为基准,计算等比宽度(上下留黑边) newWidth = windowHeight * targetRatio; newHeight = windowHeight; } else { // 窗口更高 → 以宽度为基准,计算等比高度(左右留黑边) newWidth = windowWidth; newHeight = windowWidth / targetRatio; } gameContainer.style.width = `${Math.round(newWidth)}px`; gameContainer.style.height = `${Math.round(newHeight)}px`; gameContainer.style.margin = 'auto'; // 水平垂直居中(需配合 display: block) } // 初始化 + 监听窗口变化 window.addEventListener('resize', resizeGame, { passive: true }); resizeGame(); // 首次加载即生效 </script></pre><h3>? 必要的 CSS 配合(请确认 index.html 中已包含)<p>确保 #unity-container 具备以下基础样式(Unity 默认模板通常已含部分,但需检查补全):<pre class="brush:php;toolbar:false;">#unity-container { position: absolute; top: 0; left: 0; width: 100%; height: 100%; margin: auto; overflow: hidden; display: flex; justify-content: center; align-items: center; }</pre><blockquote><p>⚠️ 注意事项:<ul><li><strong>不要对 #unity-canvas 或 canvas 元素直接设置宽高,否则会覆盖 Unity 运行时的自动缩放逻辑;<li>resize 事件监听建议使用 { passive: true } 提升滚动性能;<li>若使用自定义容器 ID(非 unity-container),请同步修改 JS 中的 getElementById 参数;<li>对于移动端 Safari,可额外添加 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> 防止双击缩放干扰;<li>如需响应式背景(如渐变或图片),建议将背景设在 body 或外层 wrapper,而非 #unity-container。<h3>✅ 效果验证<ul><li>窗口宽高比 ≥ 16:9(如 1920×1080)→ 游戏高度占满,左右留黑边;<li>窗口宽高比 < 16:9(如 1280×1024)→ 游戏宽度占满,上下留黑边;<li>所有缩放/旋转/全屏操作均实时响应,无闪烁或错位。<p>该方案完全兼容 Unity WebGL 2021.3+ 及主流浏览器(Chrome、Firefox、Edge、Safari),无需修改 C# 代码或 Unity Player Settings,是轻量、稳定、生产就绪的标准化解决方案。 </script>











