Unity WebGL Canvas 窗口自适应

 • 

Unity WebGL 一个很奇怪的事情就是默认的模板没有默认充满窗口的选项,这个问题貌似可以在 WebGL Templates 里面纯 css 解决,不过我还是更偏向于 js 一些。
以下代码 Unity 2017.3.0f3 测试可用。

// CanvasResizerPlugin.jslib
var CanvasResizerPlugin =
  {
    CanvasResizerCheckBegin: function () {
      
      function ResizeCanvas ()
      {
        try {
          document.getElementById("gameContainer").style.width =
            (window.innerWidth
              || document.documentElement.clientWidth
              || document.body.clientWidth) + "px";
          document.getElementById("#canvas").width = window.innerWidth
            || document.documentElement.clientWidth
            || document.body.clientWidth;
          document.getElementById("gameContainer").style.height =
            (window.innerHeight
              || document.documentElement.clientHeight
              || document.body.clientHeight) + "px";
          document.getElementById("#canvas").height = window.innerHeight
            || document.documentElement.clientHeight
            || document.body.clientHeight;
        }
        catch (err) {
          console.log(err);
        }
      }
      document.body.style.margin = "0px";

      window.addEventListener('resize', function (event) 
      {
        ResizeCanvas();
      });
    }
  };
mergeInto(LibraryManager.library, CanvasResizerPlugin);
// WindowResizerManager.cs
public class WindowResizerManager : Singleton<WindowResizerManager> 
    {

        [DllImport("__Internal")]
        private static extern void CanvasResizerCheckBegin();
 
        private void BeginResizeUpdating () 
        {
#if UNITY_WEBGL && !UNITY_EDITOR
			CanvasResizerCheckBegin ();
			#endif
        }

        private void Start()
        {
            try
            {
                BeginResizeUpdating();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }

效果: