利用 HTML 开发高性能的游戏

高寒蕊 (Hanrui Gao)

  -   北京

自我介绍

+


@


Blog: www.enjoyhtml5.com

内容

动画控制

忘掉你的旧习惯!

你一定用过下面这种实现方法:

window.setTimeout(function() {
  // move element. Call this again.
}, 0);

但现在,我们向您推荐:

window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame || window.msRequestAnimationFrame;

var reqId_ = null;
(function callback(time) { // time is the Unix time.
  // move element.
  reqId_ = window.requestAnimationFrame(callback, opt_elem /* bounding elem */);
})();

例子

function draw() {
  var now = new Date().getTime();
  // update models.
  paintScene(canvas);
  window.setTimeout(draw, 10);
}
draw();

function draw(time) {
  // update models.
  paintScene(canvas);
  window.requestAnimationFrame(draw, canvas);
}
draw();

使用引擎,事半功倍

使用物理引擎 Box2dWeb 的程序结构

Entity class hierarchy with update and draw methods

页面可见性

判断你的网页是否真的可见:

document.addEventListener('visibilitychange', function(e) {
  console.log('hidden:' + document.hidden,
              'state:' + document.visibilityState)
}, false);

Demo



内建时钟,精确同步时间片

资源管理

使用资源管理类

function AssetManager() {
  this.successCount = 0;
  this.errorCount = 0;
  this.cache = {};
  this.downloadQueue = [];
}

AssetManager.prototype.queueDownload = function(path) {
  this.downloadQueue.push(path);
}

AssetManager.prototype.isDone = function() {
  return (this.downloadQueue.length ==
          this.successCount + this.errorCount);
}

使用资源管理类 (续)

AssetManager.prototype.downloadAll = function(callback) {
  for (var i = 0; i < this.downloadQueue.length; i++) {
      var path = this.downloadQueue[i];
      var img = new Image();
      var that = this;
      img.addEventListener("load", function() {
          that.successCount += 1;
          if (that.isDone()) { callback(); }
      });
      img.addEventListener("error", function() {
          that.errorCount += 1;
          if (that.isDone()) { callback(); }
      });
      img.src = path;
      this.cache[path] = img;
  }
}

优化 Canvas 绘制代码

Everyone is doing their own thing

计量

每一次渲染中的主要步骤

  1. 更新 DOM
  2. 解析(render)每个元素
  3. 把解析后的所有元素汇集到浏览器窗口(browser window)
  4. 把浏览器窗口展现给用户

性能监测的方法和工具

谢 谢 !