アニメーション等の管理用に、前回実行時からの経過時間、スタートしてからの時間、FPSを知ることのできるTickerクラスをつくってみました。
つかいかた
var ticker = new ns.Ticker(24); // FPSを渡してインスタンスを生成 setup(); function setup() { ticker.addEventListener("tick", function(evt) { // evt.delta : デルタ // evt.runTime : startしてからの時間 // evt.measuredFPS : 実際のFPS fps.innerHTML = evt.measuredFPS; update(evt.delta); draw(); }); ticker.start(); } function update(delta) { console.log(delta); } function draw() { }
的なつかいかたを想定しています。
また、 以前つくったEventDispatcher を継承しています。
JavaScript
(function(win, doc, ns) { "use strict"; var _getNow = _buildGetNow(), _getAve = _buildGetAve(); function _buildGetNow() { if (!!performance) { return function () { return performance.now(); }; } else { return function () { return new Date() - 0; }; } } function _buildGetAve(opt_maxLength) { var index = 0, array = [], maxLength = opt_maxLength || 10; function _ave() { var length = array.length, sum = 0, i; for (i = 0; i < length; ++i) { sum += array[i]; } return sum / length; } function getAve(val) { array[index] = val; index = (index + 1) % maxLength; return _ave(); } return getAve; } function Ticker(opt_fps) { var _this = this, fps = opt_fps || 24, interval = 1000 / fps, timer = null; _init(); function _init() { ns.EventDispatcher.call(_this); } _this.fps = fps; _this.interval = interval; _this.timer = timer; _this.beforeTime = null; } Ticker.prototype = new ns.EventDispatcher(); Ticker.prototype.constructor = Ticker; Ticker.prototype._check = function() { var _this = this, currentTime = _getNow(), evt = {}; evt.delta = currentTime - _this.beforeTime; evt.runTime = currentTime - _this.startTime; evt.measuredFPS = _getAve(1000 / evt.delta); _this.fireEvent("tick", _this, evt); _this.beforeTime = currentTime; _this.timer = setTimeout(function() { _this._check(); }, _this.interval); }; Ticker.prototype.start = function() { var _this = this; _this.startTime = _this.beforeTime = _getNow(); _this.timer = setTimeout(function() { _this._check(); }, _this.interval); }; Ticker.prototype.stop = function() { var _this = this; clearTimeout(_this.timer); _this.beforeTime = null; }; ns.Ticker = Ticker; })(this, document, App);
DEMO
Canvasの習作をつくるときにさっそくつかってみようと思います。
今回は以上です。