phaser/v3/src/dom/RequestAnimationFrame.js

114 lines
2.6 KiB
JavaScript
Raw Normal View History

2016-11-25 00:34:37 +00:00
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var NOOP = require('../utils/NOOP');
2016-11-25 00:34:37 +00:00
/**
* Abstracts away the use of RAF or setTimeOut for the core game update loop.
*
* @class Phaser.RequestAnimationFrame
* @constructor
* @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available.
*/
var RequestAnimationFrame = function ()
2016-11-25 00:34:37 +00:00
{
/**
* @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false.
* @default
*/
this.isRunning = false;
this.callback = NOOP;
this.tick = 0;
2016-11-25 00:34:37 +00:00
/**
* @property {boolean} isSetTimeOut - True if the browser is using setTimeout instead of rAf.
*/
this.isSetTimeOut = false;
/**
* @property {number} timeOutID - The callback setTimeout or rAf callback ID used when calling cancel.
*/
this.timeOutID = null;
var _this = this;
2016-11-25 00:34:37 +00:00
// timestamp = DOMHighResTimeStamp
var step = function (timestamp)
2016-11-25 00:34:37 +00:00
{
_this.tick = timestamp;
2016-11-25 00:34:37 +00:00
_this.callback(timestamp);
2017-04-28 02:13:32 +00:00
_this.timeOutID = window.requestAnimationFrame(step);
2016-11-25 00:34:37 +00:00
};
var stepTimeout = function ()
2016-11-25 00:34:37 +00:00
{
var d = Date.now();
_this.tick = d;
_this.callback(d);
2017-04-28 02:13:32 +00:00
_this.timeOutID = window.setTimeout(stepTimeout, _this.timeToCall);
2016-11-25 00:34:37 +00:00
};
this.step = step;
this.stepTimeout = stepTimeout;
};
RequestAnimationFrame.prototype.constructor = RequestAnimationFrame;
RequestAnimationFrame.prototype = {
2016-11-25 00:34:37 +00:00
/**
* Starts the requestAnimationFrame running or setTimeout if unavailable in browser
* @method Phaser.RequestAnimationFrame#start
*/
start: function (callback, forceSetTimeOut)
2016-11-25 00:34:37 +00:00
{
this.callback = callback;
2016-11-25 00:34:37 +00:00
this.isSetTimeOut = forceSetTimeOut;
2016-11-25 00:34:37 +00:00
this.isRunning = true;
2016-11-25 00:34:37 +00:00
var _this = this;
this.timeOutID = (forceSetTimeOut) ? window.setTimeout(_this.stepTimeout, 0) : window.requestAnimationFrame(_this.step);
},
2016-11-25 00:34:37 +00:00
/**
* Stops the requestAnimationFrame from running.
* @method Phaser.RequestAnimationFrame#stop
*/
stop: function ()
2016-11-25 00:34:37 +00:00
{
this.isRunning = false;
if (this.isSetTimeOut)
{
clearTimeout(this.timeOutID);
}
else
{
window.cancelAnimationFrame(this.timeOutID);
}
},
2016-11-25 00:34:37 +00:00
destroy: function ()
2016-11-25 00:34:37 +00:00
{
this.stop();
this.callback = NOOP;
}
2016-11-25 00:34:37 +00:00
};
2016-11-25 00:34:37 +00:00
module.exports = RequestAnimationFrame;