Невозможно наложить div на полноэкранный холст для сборки Unity WebGL

html #css #unity3d #html5-canvas #webgl

#HTML #css #unity3d #html5-холст #webgl

Вопрос:

Я хочу наложить div перед полноэкранным Unity — Canvas. Я могу наложить его, когда он не на весь экран, но не могу понять, как наложить div перед Unity Canvas, пока холст находится в полноэкранном режиме.

Я сделал загрузку CSS в index.html файл сборки Unity WebGL. Это я вставляю ниже.

 <style>
  .loader {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 999;
    width: 120px;
    height: 120px;
    margin: -76px 0 0 -76px;
    border: 16px solid #f3f3f3;
    border-radius: 50%;
    border-top: 16px solid #babfc2;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;
  }
  
  /* Safari */
  @-webkit-keyframes spin {
    0% { -webkit-transform: rotate(0deg); }
    100% { -webkit-transform: rotate(360deg); }
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  </style>
    <div id="modelLoading" class="loader"></div>
 

Я использую этот CSS как класс для div, в основном div отображается в обычном окне, как показано на рисунке ниже, но он исчезает в полноэкранном окне. Также пробовал: полноэкранные вещи, но не сработало.

Я добавляю скриншоты и полный HTML-код ниже.

Спасибо за вашу помощь.

введите описание изображения здесь

введите описание изображения здесь

 <!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | DeleteThisWebGLMultiThreadWorks2</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
  </head>
  <body>
    <style>
      .loader {
        position: absolute;
        left: 50%;
        top: 50%;
        z-index: 999;
        width: 120px;
        height: 120px;
        margin: -76px 0 0 -76px;
        border: 16px solid #f3f3f3;
        border-radius: 50%;
        border-top: 16px solid #babfc2;
        -webkit-animation: spin 2s linear infinite;
        animation: spin 2s linear infinite;
      }
      
      /* Safari */
      @-webkit-keyframes spin {
        0% { -webkit-transform: rotate(0deg); }
        100% { -webkit-transform: rotate(360deg); }
      }
      
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      </style>
        <div id="modelLoading" class="loader"></div>

    <div id="unity-container" class="unity-desktop">
      <canvas id="unity-canvas" width=960 height=600>
      </canvas>
      <div id="unity-loading-bar">
        <div id="unity-logo"></div>
        <div id="unity-progress-bar-empty">
          <div id="unity-progress-bar-full"></div>
        </div>
      </div>
      <div id="unity-warning"> </div>
      <div id="unity-footer">
        <div id="unity-webgl-logo"></div>
        <div id="unity-fullscreen-button"></div>
        <div id="unity-build-title">DeleteThisWebGLMultiThreadWorks2</div>
      </div>
    </div>
    <script>
      var container = document.querySelector("#unity-container");
      var canvas = document.querySelector("#unity-canvas");
      var loadingBar = document.querySelector("#unity-loading-bar");
      var progressBarFull = document.querySelector("#unity-progress-bar-full");
      var fullscreenButton = document.querySelector("#unity-fullscreen-button");
      var warningBanner = document.querySelector("#unity-warning");

      // Shows a temporary message banner/ribbon for a few seconds, or
      // a permanent error message on top of the canvas if type=='error'.
      // If type=='warning', a yellow highlight color is used.
      // Modify or remove this function to customize the visually presented
      // way that non-critical warnings and error messages are presented to the
      // user.
      function unityShowBanner(msg, type) {
        function updateBannerVisibility() {
          warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
        }
        var div = document.createElement('div');
        div.innerHTML = msg;
        warningBanner.appendChild(div);
        if (type == 'error') div.style = 'background: red; padding: 10px;';
        else {
          if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
          setTimeout(function() {
            warningBanner.removeChild(div);
            updateBannerVisibility();
          }, 5000);
        }
        updateBannerVisibility();
      }

      var buildUrl = "Build";
      var loaderUrl = buildUrl   "/DeleteThisTryingMultiThreadWebGL8.loader.js";
      var config = {
        dataUrl: buildUrl   "/DeleteThisTryingMultiThreadWebGL8.data.gz",
        frameworkUrl: buildUrl   "/DeleteThisTryingMultiThreadWebGL8.framework.js.gz",
        codeUrl: buildUrl   "/DeleteThisTryingMultiThreadWebGL8.wasm.gz",
        streamingAssetsUrl: "StreamingAssets",
        companyName: "DefaultCompany",
        productName: "DeleteThisWebGLMultiThreadWorks2",
        productVersion: "0.1",
        showBanner: unityShowBanner,
      };

      // By default Unity keeps WebGL canvas render target size matched with
      // the DOM size of the canvas element (scaled by window.devicePixelRatio)
      // Set this to false if you want to decouple this synchronization from
      // happening inside the engine, and you would instead like to size up
      // the canvas DOM size and WebGL render target sizes yourself.
      // config.matchWebGLToCanvasSize = false;

      if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
        // Mobile device style: fill the whole browser client area with the game canvas:

        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
        document.getElementsByTagName('head')[0].appendChild(meta);
        container.className = "unity-mobile";

        // To lower canvas resolution on mobile devices to gain some
        // performance, uncomment the following line:
        // config.devicePixelRatio = 1;

        canvas.style.width = window.innerWidth   'px';
        canvas.style.height = window.innerHeight   'px';

        unityShowBanner('WebGL builds are not supported on mobile devices.');
      } else {
        // Desktop style: Render the game canvas in a window that can be maximized to fullscreen:

        canvas.style.width = "960px";
        canvas.style.height = "600px";
      }

      loadingBar.style.display = "block";

      var script = document.createElement("script");
      script.src = loaderUrl;
      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 100 * progress   "%";
        }).then((unityInstance) => {
          loadingBar.style.display = "none";
          fullscreenButton.onclick = () => {
            unityInstance.SetFullscreen(1);
          };
        }).catch((message) => {
          alert(message);
        });
      };
      document.body.appendChild(script);
    </script>
  </body>
</html>
 

Комментарии:

1. Что именно вы имеете в виду CSS show up ? CSS — это таблица стилей, которая определяет, как должны выглядеть / вести себя определенные элементы … если эти элементы не видны, потому что вы находитесь в полноэкранном режиме, то CSS здесь ни при чем…

2. Извините за неправильное определение, я мало что знаю о интерфейсных вещах. На самом деле, как вы предупреждаете, есть div, который имеет CSS в качестве своего класса. Этот div отображается в обычном режиме, но не отображается в полноэкранном режиме. В CSS можно определить класс:fullscreen, который может изменять поведение CSS в полноэкранном режиме, поэтому я полагаю, что это связано с CSS.

3. Извините, я действительно не понимаю, чего именно вы пытаетесь достичь. Если вы переходите в полноэкранный режим, предполагается, что отображается только проигрыватель WebGL, без дальнейшего содержимого HTML… вы можете оставить полноэкранный режим, нажав escape

4. Я просто упростил вопрос, я на самом деле загружаю 3D-модели во время выполнения, но при загрузке модели экран WebGL зависает и не отвечает в это время. Я просто хочу сделать экран загрузки без WebGL, чтобы пользователи не понимали, что WebGL зависает.

5. Ах, теперь я понял. Вы имеете в виду, что загрузка circle thingy исчезает из-за полноэкранного режима. Я думаю, вариантов не так много: либо встроить это в сам Unity и сделать загрузку вашего объекта максимально «асинхронной», либо использовать специальный код JavaScript, с которым ваш код c # может взаимодействовать и вызывать определенные события, на которых вы включаете и отключаете это наложение / элемент загрузки и выход / скрытие WebGLсодержимое между тем

Ответ №1:

Вместо того, чтобы просить библиотеку Unity сделать холст полноэкранным, вы можете сделать весь контейнер canvas полноэкранным самостоятельно, используя JavaScript и DOM API. Таким образом, у вас будет больше контроля. Смотрите демонстрационный код ниже. Объяснение содержится в комментариях к коду.
Поскольку вы не поделились своими библиотеками CSS и javascript, я добавил свой собственный стиль для демонстрации.
Поместите весь этот код в локальный HTML-файл и запустите его в браузере. Затем нажмите Fullscreen . Вы заметите, что загрузчик вращается в полноэкранном режиме вместе с холстом.

 <!DOCTYPE html>
<html lang="en-us">

<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Unity WebGL Player | DeleteThisWebGLMultiThreadWorks2</title>
  <link rel="shortcut icon" href="TemplateData/favicon.ico">
  <link rel="stylesheet" href="TemplateData/style.css">
  <style>
    .loader {
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 999;
      width: 120px;
      height: 120px;
      margin: -76px 0 0 -76px;
      border: 16px solid #f3f3f3;
      border-radius: 50%;
      border-top: 16px solid #babfc2;
      -webkit-animation: spin 2s linear infinite;
      animation: spin 2s linear infinite;
    }

    /* Safari */

    @-webkit-keyframes spin {
      0% {
        -webkit-transform: rotate(0deg);
      }

      100% {
        -webkit-transform: rotate(360deg);
      }
    }

    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }

    /* new rules ********/

    #unity-container {
      width: 97vw;
      height: 90vh;
      border: 3px solid orange;
      background-color: gray;
    }

    #fullScreenContainer {
      position: relative;
      height: 100%;
      width: 100%;
    }

    #unity-canvas {
      background-color: black;
      /* note the dimensions are in percentages */
      /* they'll scale with parent, as parent goes fullscreen*/
      /* the canvas will grow as well*/
      width: 100%;
      height: 100%;
      margin: 0 auto;
    }

    #unity-fullscreen-button {
      border: 1px solid black;
      width: fit-content;
      color: Orange;
      font-size: 2em;
    }

    #unity-fullscreen-button:hover {
      background-color: lightgreen;
    }

    body {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
  </style>
</head>

<body>
  <div id="unity-container" class="unity-desktop">

    <!-- take this container fullscreen instead of taking only the canvas -->
    <div id="fullScreenContainer">
      <div id="modelLoading" class="loader"></div>
      <canvas id="unity-canvas"></canvas>
    </div>

    <div id="unity-footer">
      <div id="unity-fullscreen-button">FullScreen</div>
    </div>
  </div>
  <script>
    var container = document.querySelector("#unity-container");
    var fullContainer = document.querySelector("#fullScreenContainer");
    var fullscreenButton = document.querySelector("#unity-fullscreen-button");

    fullscreenButton.onclick = () => {
      //don't request fullscreen on unityinstance
      //unityInstance.SetFullscreen(1);

      //let's take things fullscreen ourselves
      //request fullscreen on the wrapper
      fullContainer.requestFullscreen();
      //you might want to resize canvas to fit screen.

    };

    //ignore this just for the demo
    var canvas = document.getElementById("unity-canvas");
    var ctx = canvas.getContext("2d");
    ctx.font = "bold 24px verdana, sans-serif";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillStyle = "green";
    ctx.fillText("The Game", 150, 80);

    ctx.closePath();
  </script>
</body>

</html>

 

Я думаю, что если вы выполняете отладку unityInstance.SetFullscreen(1) в Chrome developer console, вы обнаружите, что он делает то же самое: изменяет размер холста и вызывает requestFullscreen() его.

Примечание: StackOverflow и другие онлайн-редакторы html не поддерживают полноэкранный режим, поэтому вам придется попробовать код в локальном файле .html.


С исправлением ваш код будет выглядеть так:

 <!DOCTYPE html>
<html lang="en-us">

<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title> Xplore 3D Model Editor</title>
  <link rel="shortcut icon" href="TemplateData/favicon.ico">
  <link rel="stylesheet" href="TemplateData/style.css">
  <style>
    #modelLoading {
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 1;
      width: 120px;
      height: 120px;
      margin: -76px 0 0 -76px;
      border: 16px solid #f3f3f3;
      border-radius: 50%;
      border-top: 16px solid #babfc2;
      -webkit-animation: spin 2s linear infinite;
      animation: spin 2s linear infinite;
    }

    #modelLoading:fullscreen {
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 1;
      width: 120px;
      height: 120px;
      margin: -76px 0 0 -76px;
      border: 16px solid #f3f3f3;
      border-radius: 50%;
      border-top: 16px solid #babfc2;
      -webkit-animation: spin 2s linear infinite;
      animation: spin 2s linear infinite;
    }

    /* Safari */
    @-webkit-keyframes spin {
      0% {
        -webkit-transform: rotate(0deg);
      }

      100% {
        -webkit-transform: rotate(360deg);
      }
    }

    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }

  </style>
</head>

<body>
  <div id="unity-container" class="unity-desktop">
    <div id="modelLoadingContainer">
      <div id="modelLoading"></div>
      <!-- //*** removed inline dimensions. setting inline style is not good -->
      <canvas id="unity-canvas"></canvas>
    </div>
    <div id="unity-loading-bar">
      <div id="unity-logo"></div>
      <div id="unity-progress-bar-empty">
        <div id="unity-progress-bar-full"></div>
      </div>
    </div>
    <div id="unity-warning"> </div>
    <div id="unity-footer">
      <div id="unity-webgl-logo"></div>

      <div id="unity-fullscreen-button">
      </div>
      <div id="unity-build-title">Xplore 3D Model Editor</div>
    </div>
  </div>
  <script>
    var container = document.querySelector("#unity-container");
    var canvas = document.querySelector("#unity-canvas");
    var loadingBar = document.querySelector("#unity-loading-bar");
    var progressBarFull = document.querySelector("#unity-progress-bar-full");
    var fullscreenButton = document.querySelector("#unity-fullscreen-button");
    var warningBanner = document.querySelector("#unity-warning");
    var modelLoading = document.getElementById('modelLoading');

    function EnableModelLoading() {
      document.getElementById("modelLoading").style.display = "";
    }
    function DisableleModelLoading() {
      document.getElementById("modelLoading").style.display = "none";
    }

    // Shows a temporary message banner/ribbon for a few seconds, or
    // a permanent error message on top of the canvas if type=='error'.
    // If type=='warning', a yellow highlight color is used.
    // Modify or remove this function to customize the visually presented
    // way that non-critical warnings and error messages are presented to the
    // user.
    function unityShowBanner(msg, type) {
      function updateBannerVisibility() {
        warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
      }
      var div = document.createElement('div');
      div.innerHTML = msg;
      warningBanner.appendChild(div);
      if (type == 'error') div.style = 'background: red; padding: 10px;';
      else {
        if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
        setTimeout(function () {
          warningBanner.removeChild(div);
          updateBannerVisibility();
        }, 5000);
      }
      updateBannerVisibility();
    }

    var buildUrl = "Build";
    var loaderUrl = buildUrl   "/Xplore3DModelEditorOnHeroku5.loader.js";
    var config = {
      dataUrl: buildUrl   "/Xplore3DModelEditorOnHeroku5.data.unityweb",
      frameworkUrl: buildUrl   "/Xplore3DModelEditorOnHeroku5.framework.js.unityweb",
      codeUrl: buildUrl   "/Xplore3DModelEditorOnHeroku5.wasm.unityweb",
      streamingAssetsUrl: "StreamingAssets",
      companyName: "Timelooper",
      productName: "Xplore 3D Model Editor",
      productVersion: "0.1",
      showBanner: unityShowBanner,
    };

    // By default Unity keeps WebGL canvas render target size matched with
    // the DOM size of the canvas element (scaled by window.devicePixelRatio)
    // Set this to false if you want to decouple this synchronization from
    // happening inside the engine, and you would instead like to size up
    // the canvas DOM size and WebGL render target sizes yourself.
    // config.matchWebGLToCanvasSize = false;

    if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
      container.className = "unity-mobile";
      // Avoid draining fillrate performance on mobile devices,
      // and default/override low DPI mode on mobile browsers.
      config.devicePixelRatio = 1;
      unityShowBanner('WebGL builds are not supported on mobile devices.');
    } else {
      //*** changes set minWidth instead of fixed width 
      canvas.style.minWidth = "960px";
      canvas.style.minHeight = "600px";
      //100% will ensure canvas will be of parent size
      canvas.style.width = "100%";
      canvas.style.height = "100%";
    }
    loadingBar.style.display = "block";

    var script = document.createElement("script");
    script.src = loaderUrl;
    script.onload = () => {
      //DisableleModelLoading();
      createUnityInstance(canvas, config, (progress) => {
        progressBarFull.style.width = 100 * progress   "%";
      }).then((unityInstance) => {
        loadingBar.style.display = "none";
        //*** hide loading
        modelLoading.style.display = "none";
      }).catch((message) => {
        alert(message);
      });
    };

    document.getElementById('unity-fullscreen-button').addEventListener('click', function () {
      var elem = document.getElementById('modelLoadingContainer');
      elem.webkitRequestFullscreen();
      if (elem.requestFullscreen) {
        elem.requestFullscreen();
      } else if (elem.msRequestFullscreen) {
        elem.msRequestFullscreen();
      } else if (elem.mozRequestFullScreen) {
        elem.mozRequestFullScreen();
      } else if (elem.webkitRequestFullscreen) {
        elem.webkitRequestFullscreen();
      }
    });
    document.body.appendChild(script);

  </script>
</body>

</html>

 

Возможно, вам придется настроить стиль для fullScreenContainer элемента.

Комментарии:

1. Спасибо за вашу помощь. Да, теперь загрузка div отображается в полноэкранном режиме, но игра не отображается, и перед черным экраном можно увидеть только текст «The Game», если я удалю часть ctx, тогда появится только черный экран с загрузкой CSS.

2. Возможно, они создают свой собственный элемент canvas. Без моего исправления проверьте в инструментах Chrome Devloper, что под unity-container элементом html находится их новый холст. Как они сделали здесь, в этой демонстрации Stackblitz или демонстрации codesandbox. У меня нет настроенной среды разработки, если бы вы могли поделиться минимальным демонстрационным приложением без моего исправления в stackblitz или codesandbox, было бы здорово.

3. Я обновил ответ, добавив, как будет выглядеть весь код с исправлением. На случай, если вы пропустили часть createUnityInstance.

4. Это была небольшая проблема со стилем. Я удалил встроенный стиль и добавил процентные стили, которые также скрывали счетчик накладных после загрузки содержимого. Теперь он отображается при загрузке в первый раз, а также при загрузке модели. Вот ссылка на вставку. Выполните поиск //*** , чтобы увидеть изменения. Кстати, классная модель!

5. Да, я нашел его на Artec3d для демонстрации подобных вещей 🙂 Вы можете реорганизовать свой ответ выше в соответствии с вашими последними изменениями, чтобы помочь разработчикам Unity, таким как я, которые являются ламером в интерфейсных вещах 🙂 В заключение, большое вам спасибо за всю вашу помощь.