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());
    }
}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Cocos Creator 2.7 版本中,可以通过 `cc.loader` 模块来加载资源,并使用 `cc.ProgressBar` 组件来创建一个资源加载进度条。具体的实现步骤如下: 1. 创建一个进度条节点 在场景编辑器中创建一个节点,并添加 `cc.ProgressBar` 组件。设置进度条的样式、位置、大小等属性。 2. 加载资源时更新进度条 使用 `cc.loader` 模块加载资源时,可以使用 `onProgress` 方法监听进度,根据已经加载的资源数和总资源数来计算加载进度,并将进度条的百分比设置为相应的值。 ``` // 加载资源的过程中 cc.loader.loadResDir("resources", (completedCount, totalCount, item) => { let percent = completedCount / totalCount; progressBar.progress = percent; // 设置进度条的百分比 }, (err, assets) => { // 加载完成后的回调 }); ``` 其中,`loadResDir` 方法用于加载资源目录中的所有资源,`completedCount` 表示已经加载的资源数,`totalCount` 表示总资源数,`item` 表示当前加载的资源信息。`percent` 表示已经加载的资源数占总资源数的百分比,`progress` 是 `cc.ProgressBar` 组件的进度属性,将其设置为相应的值即可更新进度条。 3. 加载完成时隐藏进度条 当资源加载完成时,可以将进度条节点隐藏起来。 ``` // 资源加载完成后 progressNode.active = false; // 隐藏进度条节点 ``` 这样,你就可以在 Cocos Creator 2.7 中使用 `cc.loader` 模块和 `cc.ProgressBar` 组件来创建一个资源加载进度条了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值