0


cocos creator 3.6 发布web手机端 加载进度条添加

cocos creator 升级到3.x之后加载进度条取消了,测试了多个3.x版本最终以creator 3.6.3版本,构建了简单的进度加载

参考链接:

https://forum.cocos.org/t/topic/137113

打包web-mobile后,没有进度条。加载的时候只显示一个黑屏。 - Creator 3.x - Cocos中文社区

cocos creator 3.6.x 版本H5下 启动页做进度条加载 - 掘金

参考了多个实例,大部分之解决到了第一个场景的加载进度,但creater 中cc.js加载时还是会留下空白时间,所以做了个伪进度条,让进度更平滑

主要对以下文件修改

设计思路:添加个计时函数,让进度每秒都长,确保每个时间都在增长,然后在一些关键点,插入手动更新,让进度更真实平滑

//------------------中间是新增加内容-----------------------

//-------------------end-----------------

1、 style.css中添加进度条及logo的布局
html {
  -ms-touch-action: none;
}

body, canvas, div {
  display: block;
  outline: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);

  user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

/* Remove spin of input type number */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    /* display: none; <- Crashes Chrome on hover */
    -webkit-appearance: none;
    margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}

body {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 0;
  border: 0;
  margin: 0;

  cursor: default;
  color: #888;
  background-color: #333;

  text-align: center;
  font-family: Helvetica, Verdana, Arial, sans-serif;

  display: flex;
  flex-direction: column;
}

canvas {
  background-color: rgba(0, 0, 0, 0);
}

#GameDiv, #Cocos3dGameContainer, #GameCanvas {
  width: 100%;
  height: 100%;
}
/******************以下 进度条和logo **********/
.progress-bar {
  background-color: #1a1a1a;
  position: absolute;
  left: 25%;
  top: 80%;
  height: 14px;
  padding: 5px;
  width: 50%;
  /*margin: 0 -175px;         */
  border-radius: 5px;
  box-shadow: 0 1px 5px #000 inset, 0 1px 0 #444;           
}

.progress-bar span {
  display: block;
  height: 100%;
  border-radius: 3px;
  box-shadow: 0 1px 0 rgba(255, 255, 255, .5) inset;
  transition: width .4s ease-in-out; 
  background-color: #34c2e3;    
}

.stripes span {
  background-size: 30px 30px;
  background-image: linear-gradient(135deg, rgba(255, 255, 255, .15) 25%, transparent 25%,
                      transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%,
                      transparent 75%, transparent);            
  
  animation: animate-stripes 1s linear infinite;             
}

#splash {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #171717 url(./splash.png) no-repeat center;
  background-size: 45%;
}
/******************end**********/
2、 index.html中添加节点,并且启动显示
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <title>Cocos Creator | spider</title>

  <!--http://www.html5rocks.com/en/mobile/mobifying/-->
  <meta name="viewport"
        content="width=device-width,user-scalable=no,initial-scale=1,minimum-scale=1,maximum-scale=1,minimal-ui=true"/>

  <!--https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html-->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="format-detection" content="telephone=no">

  <!-- force webkit on 360 -->
  <meta name="renderer" content="webkit"/>
  <meta name="force-rendering" content="webkit"/>
  <!-- force edge on IE -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
  <meta name="msapplication-tap-highlight" content="no">

  <!-- force full screen on some browser -->
  <meta name="full-screen" content="yes"/>
  <meta name="x5-fullscreen" content="true"/>
  <meta name="360-fullscreen" content="true"/>

  <!--fix fireball/issues/3568 -->
  <!--<meta name="browsermode" content="application">-->
  <meta name="x5-page-mode" content="app">

  <!--<link rel="apple-touch-icon" href=".png" />-->
  <!--<link rel="apple-touch-icon-precomposed" href=".png" />-->

  <link rel="stylesheet" type="text/css" href="style.css"/>

</head>
<body>
  <div id="GameDiv" cc_exact_fit_screen="true">
      <div id="Cocos3dGameContainer">
        <canvas id="GameCanvas" oncontextmenu="event.preventDefault()" tabindex="99"></canvas>
      </div>
    </div>
    <!--------------添加节点 -------------->
    <div id="splash">
      <div class="progress-bar stripes">
        <span style="width: 0%"></span>
      </div>
    </div>
    <!-----------------end--------------->
  
<!-- Polyfills bundle. -->
<script src="src/polyfills.bundle.js" charset="utf-8"> </script>

<!-- SystemJS support. -->
<script src="src/system.bundle.js" charset="utf-8"> </script>

<!-- Import map -->
<script src="src/import-map.json" type="systemjs-importmap" charset="utf-8"> </script>

<script>
    System.import('./index.js').catch(function(err) { console.error(err); })
</script>
<!--------------启动显示进度 -------------->
<script type="text/javascript">
  (function () { 
      var splash = document.getElementById('splash');
      splash.style.display = 'block';
  })();
</script>
<!--------------end -------------->
</body>
</html>
3、 添加进度条更新onProgress,和自动一个计时更新函数,onProgress手动调用分的越细节,进度曲线越平滑
System.register([], function (_export, _context) {
  "use strict";

  var cc, Application;
  //---------------计时函数 和更新进度函数--------------
  var percentJd=0;
    //每秒更新进度条
  var timer =setInterval(() => {
    const now = new Date();
    //console.log(now.toString());
    if (percentJd<90) {
      percentJd=percentJd+1;
      onProgress(percentJd);
    } else{
      clearInterval(timer);
    }
  }, 1000);

    //刷新ui 及进度
  function onProgress(percent){
    //用于手动跟新,比每秒进度大就更新
    if (percent>percentJd) {
      percentJd=percent;
    }
    var progressBar = splash.querySelector('.progress-bar span');
    // var percent = 100 * finish / total;
    if (progressBar) {
      progressBar.style.width = percent + '%';
    }
  }
  //---------------------------end-----------------

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

  return {
    setters: [],
    execute: function () {
      _export("Application", Application = /*#__PURE__*/function () {
        function Application() {
          _classCallCheck(this, Application);

          this.settingsPath = 'src/settings.json';
          this.showFPS = false;
        }

        _createClass(Application, [{
          key: "init",
          value: function init(engine) {
            cc = engine;
            cc.game.onPostBaseInitDelegate.add(this.onPostInitBase.bind(this));
            cc.game.onPostSubsystemInitDelegate.add(this.onPostSystemInit.bind(this));
          }
        }, {
          key: "onPostInitBase",
          value: function onPostInitBase() {// cc.settings.overrideSettings('assets', 'server', '');
            // do custom logic
          }
        }, {
          key: "onPostSystemInit",
          value: function onPostSystemInit() {// do custom logic
          }
        }, {
          key: "start",
          value: function start() {、
            //---------------手动更新进度条--------------
            //上面的其他函数中可以拆分更细致
            onProgress(50);,
            //game.init,初始化第一个场景,第一个场景比较大的话也会比较耗时,所以定在50%
            //----------------------------------------
            return cc.game.init({
              debugMode: false ? cc.DebugMode.INFO : cc.DebugMode.ERROR,
              settingsPath: this.settingsPath,
              overrideSettings: {
                // assets: {
                //      preloadBundles: [{ bundle: 'main', version: 'xxx' }],
                // }
                profiling: {
                  showFPS: this.showFPS
                }
              }
            }).then(function () {
              return cc.game.run();
            });
          }
        }]);

        return Application;
      }());
    }
  };
});
4、关闭进度条和logo的显示的监听
System.register(["./application.js"], function (_export, _context) {
  "use strict";

  var Application, canvas, $p, bcr, application;

  //------注册第一个场景 是否加载完成监听-----------------
  function setLoadingDisplay () {
    console.log('Engine is initialized');
    cc.director.once(cc.Director.EVENT_AFTER_SCENE_LAUNCH, function () {
      console.log('game run over' );  
        //关闭进度条显示
      splash.style.display = 'none';
        //关闭计时,但有时无效,未找到原因,有好的修改方案告知下
        if (application.timer) {
          clearInterval(application.timer);
        }
    });
  }
    //------ end-----------------

  function topLevelImport(url) {
    return System["import"](url);
  }

  return {
    setters: [function (_applicationJs) {
      Application = _applicationJs.Application;
    }],
    execute: function () {
      canvas = document.getElementById('GameCanvas');
      $p = canvas.parentElement;
      bcr = $p.getBoundingClientRect();
      canvas.width = bcr.width;
      canvas.height = bcr.height;
      application = new Application();
      topLevelImport('cc').then(function (engine) {
        //------cc 文件加载完后,添加监听-----------------
        setLoadingDisplay();
        //------end-----------------
        return application.init(engine);
      }).then(function () {
        return application.start();
      })["catch"](function (err) {
        console.error(err);
      });
    }
  };
});
以上就是全部修改内容,但由于每次发布都得修改,所以我将以上内容放入到引擎默认模板中,splash.png放在了项目模板下,就可以勾选md5 也不会更新不到了
5、修改引擎模板

路劲:F:\cocos-dashboard-editors\3.6.3\resources\resources\3d\engine\templates\web-mobile

index.html-》index.ejs

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <title><%= projectName %></title>

  <!--http://www.html5rocks.com/en/mobile/mobifying/-->
  <meta name="viewport"
        content="width=device-width,user-scalable=no,initial-scale=1,minimum-scale=1,maximum-scale=1,minimal-ui=true"/>

  <!--https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html-->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="format-detection" content="telephone=no">

  <!-- force webkit on 360 -->
  <meta name="renderer" content="webkit"/>
  <meta name="force-rendering" content="webkit"/>
  <!-- force edge on IE -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
  <meta name="msapplication-tap-highlight" content="no">

  <!-- force full screen on some browser -->
  <meta name="full-screen" content="yes"/>
  <meta name="x5-fullscreen" content="true"/>
  <meta name="360-fullscreen" content="true"/>

  <!--fix fireball/issues/3568 -->
  <!--<meta name="browsermode" content="application">-->
  <meta name="x5-page-mode" content="app">

  <!--<link rel="apple-touch-icon" href=".png" />-->
  <!--<link rel="apple-touch-icon-precomposed" href=".png" />-->

  <link rel="stylesheet" type="text/css" href="<%= cssUrl %>"/>

</head>
<body>
  <div id="GameDiv" cc_exact_fit_screen="true">
      <div id="Cocos3dGameContainer">
        <canvas id="GameCanvas" oncontextmenu="event.preventDefault()" tabindex="99"></canvas>
      </div>
    </div>
    <div id="splash">
      <div class="progress-bar stripes">
        <span style="width: 0%"></span>
      </div>
    </div>
  <%- include(cocosTemplate, {}) %>

  <script type="text/javascript">
    (function () {
   
        var splash = document.getElementById('splash');
        splash.style.display = 'block';
    })();
  </script>
</body>
</html>

index.js-》index.js.ejs

import { Application } from '<%= applicationJS %>';

const canvas = document.getElementById('GameCanvas');
const $p = canvas.parentElement;
const bcr = $p.getBoundingClientRect();
canvas.width = bcr.width;
canvas.height = bcr.height;

// 是否加载执行完成
function setLoadingDisplay () {
  console.log('Engine is initialized');
  cc.director.once(cc.Director.EVENT_AFTER_SCENE_LAUNCH, function () {
    console.log('game run over' );  
    splash.style.display = 'none';
      if (application.timer) {
        clearInterval(application.timer);
      }
  });
}

function topLevelImport (url) {
    return System.import(url);
}

const application = new Application();

topLevelImport('cc')
.then((engine) => {
     //监听
    setLoadingDisplay();
    return application.init(engine);
}).then(() => {
    return application.start();
}).catch((err) => {
    console.error(err);
});

style.css

html {
  -ms-touch-action: none;
}

body, canvas, div {
  display: block;
  outline: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);

  user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

/* Remove spin of input type number */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    /* display: none; <- Crashes Chrome on hover */
    -webkit-appearance: none;
    margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}

body {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 0;
  border: 0;
  margin: 0;

  cursor: default;
  color: #888;
  background-color: #333;

  text-align: center;
  font-family: Helvetica, Verdana, Arial, sans-serif;

  display: flex;
  flex-direction: column;
}

canvas {
  background-color: rgba(0, 0, 0, 0);
}

#GameDiv, #Cocos3dGameContainer, #GameCanvas {
  width: 100%;
  height: 100%;
}
/********************进度条********************/
.progress-bar {
  background-color: #1a1a1a;
  position: absolute;
  left: 25%;
  top: 80%;
  height: 14px;
  padding: 5px;
  width: 50%;
  /*margin: 0 -175px;         */
  border-radius: 5px;
  box-shadow: 0 1px 5px #000 inset, 0 1px 0 #444;           
}

.progress-bar span {
  display: block;
  height: 100%;
  border-radius: 3px;
  box-shadow: 0 1px 0 rgba(255, 255, 255, .5) inset;
  transition: width .4s ease-in-out; 
  background-color: #34c2e3;    
}

.stripes span {
  background-size: 30px 30px;
  background-image: linear-gradient(135deg, rgba(255, 255, 255, .15) 25%, transparent 25%,
                      transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%,
                      transparent 75%, transparent);            
  
  animation: animate-stripes 1s linear infinite;             
}

#splash {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #171717 url(./splash.png) no-repeat center;
  background-size: 45%;
}

application.js-》application.ejs

F:\cocos-dashboard-editors\3.6.3\resources\resources\3d\engine\templates\launcher

<%- include(versionCheckTemplate, { version: '1.0.0'}) %>
let cc;

//---------------自动 updata Progress--------------
var percentJd=0;
var timer =setInterval(() => {
  const now = new Date();
  //console.log(now.toString());
  if (percentJd<90) {
    percentJd=percentJd+1;
    onProgress(percentJd);
  } else{
    clearInterval(timer);
  }
}, 1000);

function onProgress(percent){
  if (percent>percentJd) {
    percentJd=percent;
  }
  var progressBar = splash.querySelector('.progress-bar span');
  // var percent = 100 * finish / total;
  if (progressBar) {
    progressBar.style.width = percent + '%';
  }
}
//------------end-----------------

export class Application {
    constructor () {
        this.settingsPath = '<%= settingsJsonPath %>';
        this.showFPS = <%= showFPS %>;
    }
    

    init (engine) {
        cc = engine;
        cc.game.onPostBaseInitDelegate.add(this.onPostInitBase.bind(this));
        cc.game.onPostSubsystemInitDelegate.add(this.onPostSystemInit.bind(this));
    }

    onPostInitBase () {
        // cc.settings.overrideSettings('assets', 'server', '');
        // do custom logic
    }

    onPostSystemInit () {
        // do custom logic
    }

    start () {
        // 手动更新
        onProgress(50);
        return cc.game.init({
            debugMode: <%= debugMode %> ? cc.DebugMode.INFO : cc.DebugMode.ERROR,
            settingsPath: this.settingsPath,
            overrideSettings: {
                // assets: {
                //      preloadBundles: [{ bundle: 'main', version: 'xxx' }],
                // }
                profiling: {
                    showFPS: this.showFPS,
                }
            }
        }).then(() => cc.game.run());
    }
}
标签: cocos creator

本文转载自: https://blog.csdn.net/weixin_41843959/article/details/138012457
版权归原作者 落水无痕 所有, 如有侵权,请联系我们删除。

“cocos creator 3.6 发布web手机端 加载进度条添加”的评论:

还没有评论