phaser-ce
Version:
Phaser CE (Community Edition) is a fast, free and fun HTML5 Game Framework for Desktop and Mobile web browsers.
1,466 lines (1,289 loc) • 82.5 kB
JavaScript
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @classdesc
* The ScaleManager object handles the the scaling, resizing, and alignment of the
* Game size and the game Display canvas.
*
* The Game size is the logical size of the game; the Display canvas has size as an HTML element.
*
* The calculations of these are heavily influenced by the bounding Parent size which is the computed
* dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the
* canvas's Parent element play an important role_ in the operation of the ScaleManager.
*
* The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size.
* When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}).
*
* #### Parent and Display canvas containment guidelines:
*
* - Style the Parent element (of the game canvas) to control the Parent size and
* thus the Display canvas's size and layout.
*
* - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior.
*
* - The Parent element should _not_ apply a padding as this is not accounted for.
* If a padding is required apply it to the Parent's parent or apply a margin to the Parent.
* If you need to add a border, margin or any other CSS around your game container, then use a parent element and
* apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container.
*
* - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as
* they may be updated by the ScaleManager.
*
* #### Example Uses
*
* - ##### Fixed game size; scale canvas proportionally to fill its container
*
* Use `scaleMode` SHOW_ALL.
*
* - ##### Fixed game size; stretch canvas to fill its container (uncommon)
*
* Use `scaleMode` EXACT_FIT.
*
* - ##### Fixed game size; scale canvas proportionally by some other criteria
*
* Use `scaleMode` USER_SCALE. Examine `parentBounds` in the {@link #setResizeCallback resize callback} and call {@link #setUserScale} if necessary.
*
* - ##### Fluid game/canvas size
*
* Use `scaleMode` RESIZE. Examine the game or canvas size from the {@link #onSizeChange} signal **or** the {@link Phaser.State#resize} callback and reposition game objects if necessary.
*
* - ##### Preferred orientation
*
* Call {@link #forceOrientation} with the preferred orientation and use any of the {@link #onOrientationChange}, {@link #enterIncorrectOrientation}, or {@link #leaveIncorrectOrientation} signals.
*
* @description
* Create a new ScaleManager object - this is done automatically by {@link Phaser.Game}
*
* The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%.
*
* @class
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number|string} width - The width of the game. See above.
* @param {number|string} height - The height of the game. See above.
*/
Phaser.ScaleManager = function (game, width, height)
{
/**
* A reference to the currently running game.
* @property {Phaser.Game} game
* @protected
* @readonly
*/
this.game = game;
/**
* Provides access to some cross-device DOM functions.
* @property {Phaser.DOM} dom
* @protected
* @readonly
*/
this.dom = Phaser.DOM;
/**
* _EXPERIMENTAL:_ A responsive grid on which you can align game objects.
* @property {Phaser.FlexGrid} grid
* @public
*/
this.grid = null;
/**
* Target width (in pixels) of the Display canvas.
* @property {number} width
* @readonly
*/
this.width = 0;
/**
* Target height (in pixels) of the Display canvas.
* @property {number} height
* @readonly
*/
this.height = 0;
/**
* Minimum width the canvas should be scaled to (in pixels).
* Change with {@link #setMinMax}.
* @property {?number} minWidth
* @readonly
* @protected
*/
this.minWidth = null;
/**
* Maximum width the canvas should be scaled to (in pixels).
* If null it will scale to whatever width the browser can handle.
* Change with {@link #setMinMax}.
* @property {?number} maxWidth
* @readonly
* @protected
*/
this.maxWidth = null;
/**
* Minimum height the canvas should be scaled to (in pixels).
* Change with {@link #setMinMax}.
* @property {?number} minHeight
* @readonly
* @protected
*/
this.minHeight = null;
/**
* Maximum height the canvas should be scaled to (in pixels).
* If null it will scale to whatever height the browser can handle.
* Change with {@link #setMinMax}.
* @property {?number} maxHeight
* @readonly
* @protected
*/
this.maxHeight = null;
/**
* The offset coordinates of the Display canvas from the top-left of the browser window.
* The is used internally by Phaser.Pointer (for Input) and possibly other types.
* @property {Phaser.Point} offset
* @readonly
* @protected
*/
this.offset = new Phaser.Point();
/**
* If true, the game should only run in a landscape orientation.
* Change with {@link #forceOrientation}.
* @property {boolean} forceLandscape
* @readonly
* @default
* @protected
*/
this.forceLandscape = false;
/**
* If true, the game should only run in a portrait
* Change with {@link #forceOrientation}.
* @property {boolean} forcePortrait
* @readonly
* @default
* @protected
*/
this.forcePortrait = false;
/**
* True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation.
*
* This value is not updated immediately.
*
* @property {boolean} incorrectOrientation
* @readonly
* @protected
*/
this.incorrectOrientation = false;
/**
* See {@link #pageAlignHorizontally}.
* @property {boolean} _pageAlignHorizontally
* @private
*/
this._pageAlignHorizontally = false;
/**
* See {@link #pageAlignVertically}.
* @property {boolean} _pageAlignVertically
* @private
*/
this._pageAlignVertically = false;
/**
* This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes.
*
* The signal is supplied with the following arguments:
* - `scale` - the ScaleManager object
* - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}.
* - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect.
*
* Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`.
* Thus the following tests can be done:
*
* // The orientation itself changed:
* scale.screenOrientation !== prevOrientation
* // The orientation just became incorrect:
* scale.incorrectOrientation && !wasIncorrect
*
* It is possible that this signal is triggered after {@link #forceOrientation} so the orientation
* correctness changes even if the orientation itself does not change.
*
* This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
*
* @property {Phaser.Signal} onOrientationChange
* @public
*/
this.onOrientationChange = new Phaser.Signal();
/**
* This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}.
*
* This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
*
* @property {Phaser.Signal} enterIncorrectOrientation
* @public
*/
this.enterIncorrectOrientation = new Phaser.Signal();
/**
* This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}.
*
* This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
*
* @property {Phaser.Signal} leaveIncorrectOrientation
* @public
*/
this.leaveIncorrectOrientation = new Phaser.Signal();
/**
* This boolean provides you with a way to determine if the browser is in Full Screen
* mode (via the Full Screen API), and Phaser was the one responsible for activating it.
*
* It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the
* one that made the browser go full-screen, so this flag lets you determine that.
*
* @property {boolean} hasPhaserSetFullScreen
* @default
*/
this.hasPhaserSetFullScreen = false;
/**
* If specified, this is the DOM element on which the Fullscreen API enter request will be invoked.
* The target element must have the correct CSS styling and contain the Display canvas.
*
* The elements style will be modified (ie. the width and height might be set to 100%)
* but it will not be added to, removed from, or repositioned within the DOM.
* An attempt is made to restore relevant style changes when fullscreen mode is left.
*
* For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`.
*
* @property {?DOMElement} fullScreenTarget
* @default
*/
this.fullScreenTarget = null;
/**
* The fullscreen target, as created by {@link #createFullScreenTarget}.
* This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends.
* @property {?DOMElement} _createdFullScreenTarget
* @private
*/
this._createdFullScreenTarget = null;
/**
* This signal is dispatched when fullscreen mode is ready to be initialized but
* before the fullscreen request.
*
* The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`.
*
* The `targetElement` is the {@link #fullScreenTarget} element,
* if such is assigned, or a new element created by {@link #createFullScreenTarget}.
*
* Custom CSS styling or resets can be applied to `targetElement` as required.
*
* If `targetElement` is _not_ the same element as {@link #fullScreenTarget}:
* - After initialization the Display canvas is moved onto the `targetElement` for
* the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited.
* - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated.
*
* The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}.
*
* @property {Phaser.Signal} onFullScreenInit
* @public
*/
this.onFullScreenInit = new Phaser.Signal();
/**
* This signal is dispatched when the browser enters or leaves fullscreen mode, if supported.
*
* The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine
* if currently running in Fullscreen mode.
*
* @property {Phaser.Signal} onFullScreenChange
* @public
*/
this.onFullScreenChange = new Phaser.Signal();
/**
* This signal is dispatched when the browser fails to enter fullscreen mode;
* or if the device does not support fullscreen mode and `startFullScreen` is invoked.
*
* The signal is supplied with a single argument: `scale` (the ScaleManager).
*
* @property {Phaser.Signal} onFullScreenError
* @public
*/
this.onFullScreenError = new Phaser.Signal();
/**
* The _last known_ orientation of the screen, as defined in the Window Screen Web API.
* See {@link Phaser.DOM.getScreenOrientation} for possible values.
*
* @property {string} screenOrientation
* @readonly
* @public
*/
this.screenOrientation = this.dom.getScreenOrientation();
/**
* The _current_ scale factor based on the game dimensions vs. the scaled dimensions.
* @property {Phaser.Point} scaleFactor
* @readonly
*/
this.scaleFactor = new Phaser.Point(1, 1);
/**
* The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions.
* @property {Phaser.Point} scaleFactorInversed
* @readonly
* @protected
*/
this.scaleFactorInversed = new Phaser.Point(1, 1);
/**
* The Display canvas is aligned by adjusting the margins; the last margins are stored here.
*
* @property {Bounds-like} margin
* @readonly
* @protected
*/
this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0};
/**
* The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height.
* @property {Phaser.Rectangle} bounds
* @readonly
*/
this.bounds = new Phaser.Rectangle();
/**
* The aspect ratio of the scaled Display canvas.
* @property {number} aspectRatio
* @readonly
*/
this.aspectRatio = 0;
/**
* The aspect ratio of the original game dimensions.
* @property {number} sourceAspectRatio
* @readonly
*/
this.sourceAspectRatio = 0;
/**
* The native browser events from Fullscreen API changes.
* @property {any} event
* @readonly
* @private
*/
this.event = null;
/**
* The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container.
*
* The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'.
* - If 'visual', the edge will be constrained to the Window / displayed screen area
* - If 'layout', the edge will be constrained to the CSS Layout bounds
* - An invalid value is treated as 'visual'
*
* @member
* @property {string} bottom
* @property {string} right
* @default
*/
this.windowConstraints = {
right: 'layout',
bottom: ''
};
/**
* Various compatibility settings.
* A value of "(auto)" indicates the setting is configured based on device and runtime information.
*
* A {@link #refresh} may need to be performed after making changes.
*
* @protected
*
* @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.)
*
* @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}.
*
* @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen.
*
* @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh.
*
* @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates.
* The height set varies by device and may either be the height of the window or the viewport.
*
* @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions.
*
* @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events.
* A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used.
* Any other string value (including the empty string) prevents using click trampolines.
* For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}.
*/
this.compatibility = {
supportsFullScreen: false,
orientationFallback: null,
noMargins: false,
scrollTo: null,
forceMinimumDocumentHeight: false,
canExpandParent: true,
clickTrampoline: ''
};
/**
* Scale mode to be used when not in fullscreen.
* @property {number} _scaleMode
* @private
*/
this._scaleMode = Phaser.ScaleManager.NO_SCALE;
/*
* Scale mode to be used in fullscreen.
* @property {number} _fullScreenScaleMode
* @private
*/
this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
/**
* True if the the browser window (instead of the display canvas's DOM parent) should be used as the bounding parent.
*
* This is set automatically based on the `parent` argument passed to {@link Phaser.Game}.
*
* The {@link #parentNode} property is generally ignored while this is in effect.
*
* @property {boolean} parentIsWindow
*/
this.parentIsWindow = false;
/**
* The _original_ DOM element for the parent of the Display canvas.
* This may be different in fullscreen - see {@link #createFullScreenTarget}.
*
* This is set automatically based on the `parent` argument passed to {@link Phaser.Game}.
*
* This should only be changed after moving the Game canvas to a different DOM parent.
*
* @property {?DOMElement} parentNode
*/
this.parentNode = null;
/**
* The scale of the game in relation to its parent container.
* @property {Phaser.Point} parentScaleFactor
* @readonly
*/
this.parentScaleFactor = new Phaser.Point(1, 1);
/**
* The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window).
* Update checks normally happen quicker in response to other events.
*
* @property {integer} trackParentInterval
* @default
* @protected
* @see {@link Phaser.ScaleManager#refresh refresh}
*/
this.trackParentInterval = 2000;
/**
* This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes.
* When invoked this is done _after_ the Canvas size/position have been updated.
*
* The callback is supplied with three arguments: the Scale Manager, canvas {@link #width}, and canvas {@link #height}. (Game dimensions can be found in `scale.game.width` and `scale.game.height`.)
*
* This signal is _only_ called when a change occurs and a reflow may be required.
* For example, if the canvas does not change sizes because of CSS settings (such as min-width)
* then this signal will _not_ be triggered.
*
* Use this to handle responsive game layout options.
*
* This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
*
* @property {Phaser.Signal} onSizeChange
*/
this.onSizeChange = new Phaser.Signal();
/**
* The callback that will be called each the parent container resizes.
* @property {function} onResize
* @private
*/
this.onResize = null;
/**
* The context in which the {@link #onResize} callback will be called.
* @property {object} onResizeContext
* @private
*/
this.onResizeContext = null;
/**
* @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot.
* @private
*/
this._pendingScaleMode = null;
/**
* Information saved when fullscreen mode is started.
* @property {?object} _fullScreenRestore
* @private
*/
this._fullScreenRestore = null;
/**
* The _actual_ game dimensions, as initially set or set by {@link #setGameSize}.
* @property {Phaser.Rectangle} _gameSize
* @private
*/
this._gameSize = new Phaser.Rectangle();
/**
* The user-supplied scale factor, used with the USER_SCALE scaling mode.
* @property {Phaser.Point} _userScaleFactor
* @private
*/
this._userScaleFactor = new Phaser.Point(1, 1);
/**
* The user-supplied scale trim, used with the USER_SCALE scaling mode.
* @property {Phaser.Point} _userScaleTrim
* @private
*/
this._userScaleTrim = new Phaser.Point(0, 0);
/**
* The last time the bounds were checked in `preUpdate`.
* @property {number} _lastUpdate
* @private
*/
this._lastUpdate = 0;
/**
* Size checks updates are delayed according to the throttle.
* The throttle increases to `trackParentInterval` over time and is used to more
* rapidly detect changes in certain browsers (eg. IE) while providing back-off safety.
* @property {integer} _updateThrottle
* @private
*/
this._updateThrottle = 0;
/**
* The minimum throttle allowed until it has slowed down sufficiently.
* @property {integer} _updateThrottleReset
* @private
*/
this._updateThrottleReset = 100;
/**
* The cached result of the parent (possibly window) bounds; used to invalidate sizing.
* @property {Phaser.Rectangle} _parentBounds
* @private
*/
this._parentBounds = new Phaser.Rectangle();
/**
* Temporary bounds used for internal work to cut down on new objects created.
* @property {Phaser.Rectangle} _parentBounds
* @private
*/
this._tempBounds = new Phaser.Rectangle();
/**
* The Canvas size at which the last onSizeChange signal was triggered.
* @property {Phaser.Rectangle} _lastReportedCanvasSize
* @private
*/
this._lastReportedCanvasSize = new Phaser.Rectangle();
/**
* The Game size at which the last onSizeChange signal was triggered.
* @property {Phaser.Rectangle} _lastReportedGameSize
* @private
*/
this._lastReportedGameSize = new Phaser.Rectangle();
/**
* @property {boolean} _booted - ScaleManager booted state.
* @private
*/
this._booted = false;
if (game.config)
{
this.parseConfig(game.config);
}
this.setupScale(width, height);
};
/**
* A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
*
* @constant
* @type {integer}
*/
Phaser.ScaleManager.EXACT_FIT = 0;
/**
* A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
*
* @constant
* @type {integer}
*/
Phaser.ScaleManager.NO_SCALE = 1;
/**
* A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
*
* @constant
* @type {integer}
*/
Phaser.ScaleManager.SHOW_ALL = 2;
/**
* A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
*
* @constant
* @type {integer}
*/
Phaser.ScaleManager.RESIZE = 3;
/**
* A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
*
* @constant
* @type {integer}
*/
Phaser.ScaleManager.USER_SCALE = 4;
/**
* Names of the scale modes, indexed by value.
*
* @constant
* @type {string[]}
*/
Phaser.ScaleManager.MODES = [
'EXACT_FIT',
'NO_SCALE',
'SHOW_ALL',
'RESIZE',
'USER_SCALE'
];
Phaser.ScaleManager.prototype = {
/**
* Start the ScaleManager.
*
* @method Phaser.ScaleManager#boot
* @protected
*/
boot: function ()
{
// Configure device-dependent compatibility
var compat = this.compatibility;
compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS;
// We can't do anything about the status bars in iPads, web apps or desktops
if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop)
{
if (this.game.device.android && !this.game.device.chrome)
{
compat.scrollTo = new Phaser.Point(0, 1);
}
else
{
compat.scrollTo = new Phaser.Point(0, 0);
}
}
if (this.game.device.desktop)
{
compat.orientationFallback = 'screen';
compat.clickTrampoline = 'when-not-mouse';
}
else
{
compat.orientationFallback = '';
compat.clickTrampoline = '';
}
// Configure event listeners
var _this = this;
this._orientationChange = function (event)
{
return _this.orientationChange(event);
};
this._windowResize = function (event)
{
return _this.windowResize(event);
};
// This does not appear to be on the standards track
window.addEventListener('orientationchange', this._orientationChange, false);
window.addEventListener('resize', this._windowResize, false);
if (this.compatibility.supportsFullScreen)
{
this._fullScreenChange = function (event)
{
return _this.fullScreenChange(event);
};
this._fullScreenError = function (event)
{
return _this.fullScreenError(event);
};
document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false);
document.addEventListener('mozfullscreenchange', this._fullScreenChange, false);
document.addEventListener('MSFullscreenChange', this._fullScreenChange, false);
document.addEventListener('fullscreenchange', this._fullScreenChange, false);
document.addEventListener('webkitfullscreenerror', this._fullScreenError, false);
document.addEventListener('mozfullscreenerror', this._fullScreenError, false);
document.addEventListener('MSFullscreenError', this._fullScreenError, false);
document.addEventListener('fullscreenerror', this._fullScreenError, false);
}
this.game.onResume.add(this._gameResumed, this);
// Initialize core bounds
this.dom.getOffset(this.game.canvas, this.offset);
this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height);
this.setGameSize(this.game.width, this.game.height);
// Don't use updateOrientationState so events are not fired
this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback);
if (Phaser.FlexGrid)
{
this.grid = new Phaser.FlexGrid(this, this.width, this.height);
}
this._booted = true;
if (this._pendingScaleMode !== null)
{
this.scaleMode = this._pendingScaleMode;
this._pendingScaleMode = null;
}
},
/**
* Load configuration settings.
*
* @method Phaser.ScaleManager#parseConfig
* @protected
* @param {object} config - The game configuration object.
*/
parseConfig: function (config)
{
if (config.scaleMode !== undefined)
{
if (this._booted)
{
this.scaleMode = config.scaleMode;
}
else
{
this._pendingScaleMode = config.scaleMode;
}
}
if (config.fullScreenScaleMode !== undefined)
{
this.fullScreenScaleMode = config.fullScreenScaleMode;
}
if (config.fullScreenTarget)
{
this.fullScreenTarget = config.fullScreenTarget;
}
this.pageAlignHorizontally = config.alignH || false;
this.pageAlignVertically = config.alignV || false;
if (config.scaleH && config.scaleV)
{
this.setUserScale(config.scaleH, config.scaleV, config.trimH, config.trimV);
}
},
/**
* Calculates and sets the game dimensions based on the given width and height.
*
* This should _not_ be called when in fullscreen mode.
*
* @method Phaser.ScaleManager#setupScale
* @protected
* @param {number|string} width - The width of the game.
* @param {number|string} height - The height of the game.
*/
setupScale: function (width, height)
{
var target;
var rect = new Phaser.Rectangle();
if (this.game.parent !== '')
{
if (typeof this.game.parent === 'string')
{
// hopefully an element ID
target = document.getElementById(this.game.parent);
}
else if (this.game.parent && this.game.parent.nodeType === 1)
{
// quick test for a HTMLelement
target = this.game.parent;
}
}
// Fallback, covers an invalid ID and a non HTMLelement object
if (!target)
{
// Use the full window
this.parentNode = null;
this.parentIsWindow = true;
rect.width = this.dom.visualBounds.width;
rect.height = this.dom.visualBounds.height;
this.offset.set(0, 0);
}
else
{
this.parentNode = target;
this.parentIsWindow = false;
this.getParentBounds(this._parentBounds, this.parentNode);
rect.width = this._parentBounds.width;
rect.height = this._parentBounds.height;
this.offset.set(this._parentBounds.x, this._parentBounds.y);
}
var newWidth = 0;
var newHeight = 0;
if (typeof width === 'number')
{
newWidth = width;
}
else
{
// Percentage based
this.parentScaleFactor.x = parseInt(width, 10) / 100;
newWidth = rect.width * this.parentScaleFactor.x;
}
if (typeof height === 'number')
{
newHeight = height;
}
else
{
// Percentage based
this.parentScaleFactor.y = parseInt(height, 10) / 100;
newHeight = rect.height * this.parentScaleFactor.y;
}
newWidth = Math.floor(newWidth);
newHeight = Math.floor(newHeight);
this._gameSize.setTo(0, 0, newWidth, newHeight);
this.updateDimensions(newWidth, newHeight, false);
},
/**
* Invoked when the game is resumed.
*
* @method Phaser.ScaleManager#_gameResumed
* @private
*/
_gameResumed: function ()
{
this.queueUpdate(true);
},
/**
* Set the actual Game size.
* Use this instead of directly changing `game.width` or `game.height`.
*
* The actual physical display (Canvas element size) depends on various settings including
* - Scale mode
* - Scaling factor
* - Size of Canvas's parent element or CSS rules such as min-height/max-height;
* - The size of the Window
*
* @method Phaser.ScaleManager#setGameSize
* @public
* @param {integer} width - _Game width_, in pixels.
* @param {integer} height - _Game height_, in pixels.
*/
setGameSize: function (width, height)
{
this._gameSize.setTo(0, 0, width, height);
if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE)
{
this.updateDimensions(width, height, true);
}
this.queueUpdate(true);
},
/**
* Set a User scaling factor used in the USER_SCALE scaling mode.
*
* The target canvas size is computed by:
*
* canvas.width = (game.width * hScale) - hTrim
* canvas.height = (game.height * vScale) - vTrim
*
* This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}. Set `queueUpdate` and `force` to false if the resize callback is being called repeatedly.
*
* @method Phaser.ScaleManager#setUserScale
* @param {number} hScale - Horizontal scaling factor.
* @param {numer} vScale - Vertical scaling factor.
* @param {integer} [hTrim=0] - Horizontal trim, applied after scaling.
* @param {integer} [vTrim=0] - Vertical trim, applied after scaling.
* @param {boolean} [queueUpdate=true] - Queue a size/bounds check at next preUpdate
* @param {boolean} [force=true] - Force a resize during the next preUpdate
*/
setUserScale: function (hScale, vScale, hTrim, vTrim, queueUpdate, force)
{
this._userScaleFactor.setTo(hScale, vScale);
this._userScaleTrim.setTo(hTrim | 0, vTrim | 0);
if (queueUpdate === undefined) { queueUpdate = true; }
if (force === undefined) { force = true; }
if (queueUpdate)
{
this.queueUpdate(force);
}
},
/**
* Sets the callback that will be invoked before sizing calculations.
*
* Typically this is triggered when the Scale Manager has detected a change to the canvas's boundaries:
* the browser window has been resized, the device has been rotated, or the parent container's size has changed.
* At this point the Scale Manager has not resized the game or canvas yet (and may not resize them at all
* after it makes its sizing calculations). You can read the size of the parent container from the
* `parentBounds` argument to the callback.
*
* This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling.
*
* The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager
* and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element.
*
* This callback
* - May be invoked even though the parent container or canvas sizes have not changed
* - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated
* - Will be invoked from `preUpdate`, _even when_ the game is paused
*
* See {@link #onSizeChange} for a better way of reacting to layout updates.
*
* @method Phaser.ScaleManager#setResizeCallback
* @public
* @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes.
* @param {object} context - The context in which the callback will be called.
*/
setResizeCallback: function (callback, context)
{
this.onResize = callback;
this.onResizeContext = context;
},
/**
* Signals a resize - IF the canvas or Game size differs from the last signal.
*
* This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager).
*
* It dispatches the {@link #onSizeChange} signal.
*
* @method Phaser.ScaleManager#signalSizeChange
* @private
*/
signalSizeChange: function ()
{
if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) ||
!Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize))
{
var width = this.width;
var height = this.height;
this._lastReportedCanvasSize.setTo(0, 0, width, height);
this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height);
if (this.grid)
{
this.grid.onResize(width, height);
}
this.onSizeChange.dispatch(this, width, height);
// Per StateManager#onResizeCallback, it only occurs when in RESIZE mode.
if (this.currentScaleMode === Phaser.ScaleManager.RESIZE)
{
this.game.state.resize(width, height);
this.game.load.resize(width, height);
}
}
},
/**
* Set the min and max dimensions for the Display canvas.
*
* _Note:_ The min/max dimensions are only applied in some cases
* - When the device is not in an incorrect orientation; or
* - The scale mode is EXACT_FIT when not in fullscreen
*
* @method Phaser.ScaleManager#setMinMax
* @public
* @param {number} minWidth - The minimum width the game is allowed to scale down to.
* @param {number} minHeight - The minimum height the game is allowed to scale down to.
* @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified.
* @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified.
* @todo These values are only sometimes honored.
*/
setMinMax: function (minWidth, minHeight, maxWidth, maxHeight)
{
this.minWidth = minWidth;
this.minHeight = minHeight;
if (typeof maxWidth !== 'undefined')
{
this.maxWidth = maxWidth;
}
if (typeof maxHeight !== 'undefined')
{
this.maxHeight = maxHeight;
}
},
/**
* The ScaleManager.preUpdate is called automatically by the core Game loop.
*
* @method Phaser.ScaleManager#preUpdate
* @protected
*/
preUpdate: function ()
{
if (this.game.time.time < (this._lastUpdate + this._updateThrottle))
{
return;
}
var prevThrottle = this._updateThrottle;
this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100;
this.dom.getOffset(this.game.canvas, this.offset);
var prevWidth = this._parentBounds.width;
var prevHeight = this._parentBounds.height;
var bounds = this.getParentBounds(this._parentBounds);
var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight;
// Always invalidate on a newly detected orientation change
var orientationChanged = this.updateOrientationState();
if (boundsChanged || orientationChanged)
{
if (this.onResize)
{
this.onResize.call(this.onResizeContext, this, bounds);
}
this.updateLayout();
this.signalSizeChange();
}
// Next throttle, eg. 25, 50, 100, 200..
var throttle = this._updateThrottle * 2;
// Don't let an update be too eager about resetting the throttle.
if (this._updateThrottle < prevThrottle)
{
throttle = Math.min(prevThrottle, this._updateThrottleReset);
}
this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval);
this._lastUpdate = this.game.time.time;
},
/**
* Update method while paused.
*
* @method Phaser.ScaleManager#pauseUpdate
* @private
*/
pauseUpdate: function ()
{
this.preUpdate();
// Updates at slowest.
this._updateThrottle = this.trackParentInterval;
},
/**
* Update the dimensions taking the parent scaling factor into account.
*
* @method Phaser.ScaleManager#updateDimensions
* @private
* @param {number} width - The new width of the parent container.
* @param {number} height - The new height of the parent container.
* @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars.
*/
updateDimensions: function (width, height, resize)
{
this.width = width * this.parentScaleFactor.x;
this.height = height * this.parentScaleFactor.y;
this.game.width = this.width;
this.game.height = this.height;
this.sourceAspectRatio = this.width / this.height;
this.updateScalingAndBounds();
if (resize)
{
// Resize the renderer (which in turn resizes the Display canvas!)
this.game.renderer.resize(this.width, this.height);
// The Camera can never be smaller than the Game size
this.game.camera.setSize(this.width, this.height);
// This should only happen if the world is smaller than the new canvas size
this.game.world.resize(this.width, this.height);
}
},
/**
* Update relevant scaling values based on the ScaleManager dimension and game dimensions,
* which should already be set. This does not change {@link #sourceAspectRatio}.
*
* @method Phaser.ScaleManager#updateScalingAndBounds
* @private
*/
updateScalingAndBounds: function ()
{
this.scaleFactor.x = this.game.width / this.width;
this.scaleFactor.y = this.game.height / this.height;
this.scaleFactorInversed.x = this.width / this.game.width;
this.scaleFactorInversed.y = this.height / this.game.height;
this.aspectRatio = this.width / this.height;
// This can be invoked in boot pre-canvas
if (this.game.canvas)
{
this.dom.getOffset(this.game.canvas, this.offset);
}
this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height);
// Can be invoked in boot pre-input
if (this.game.input && this.game.input.scale)
{
this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y);
}
},
/**
* Force the game to run in only one orientation.
*
* This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation.
*
* Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor
* orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the
* viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'`
*
* @method Phaser.ScaleManager#forceOrientation
* @public
* @param {boolean} forceLandscape - true if the game should run in landscape mode only.
* @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
*/
forceOrientation: function (forceLandscape, forcePortrait)
{
if (forcePortrait === undefined) { forcePortrait = false; }
if (forceLandscape === true && forcePortrait === true)
{
console.warn('Phaser.ScaleManager: forceLandscape and forcePortrait cannot both be true.');
return;
}
this.forceLandscape = forceLandscape;
this.forcePortrait = forcePortrait;
this.queueUpdate(true);
},
/**
* Classify the orientation, per `getScreenOrientation`.
*
* @method Phaser.ScaleManager#classifyOrientation
* @private
* @param {string} orientation - The orientation string, e.g. 'portrait-primary'.
* @return {?string} The classified orientation: 'portrait', 'landscape`, or null.
*/
classifyOrientation: function (orientation)
{
if (orientation === 'portrait-primary' || orientation === 'portrait-secondary')
{
return 'portrait';
}
else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary')
{
return 'landscape';
}
else
{
return null;
}
},
/**
* Updates the current orientation and dispatches orientation change events.
*
* @method Phaser.ScaleManager#updateOrientationState
* @private
* @return {boolean} True if the orientation state changed which means a forced update is likely required.
*/
updateOrientationState: function ()
{
var previousOrientation = this.screenOrientation;
var previouslyIncorrect = this.incorrectOrientation;
this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback);
this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) ||
(this.forcePortrait && !this.isPortrait);
var changed = previousOrientation !== this.screenOrientation;
var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation;
if (correctnessChanged)
{
if (this.incorrectOrientation)
{
this.enterIncorrectOrientation.dispatch();
}
else
{
this.leaveIncorrectOrientation.dispatch();
}
}
if (changed || correctnessChanged)
{
this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect);
}
return changed || correctnessChanged;
},
/**
* window.orientationchange event handler.
*
* @method Phaser.ScaleManager#orientationChange
* @private
* @param {Event} event - The orientationchange event data.
*/
orientationChange: function (event)
{
this.event = event;
this.queueUpdate(true);
},
/**
* window.resize event handler.
*
* @method Phaser.ScaleManager#windowResize
* @private
* @param {Event} event - The resize event data.
*/
windowResize: function (event)
{
this.event = event;
this.queueUpdate(true);
},
/**
* Scroll to the top - in some environments. See `compatibility.scrollTo`.
*
* @method Phaser.ScaleManager#scrollTop
* @private
*/
scrollTop: function ()
{
var scrollTo = this.compatibility.scrollTo;
if (scrollTo)
{
window.scrollTo(scrollTo.x, scrollTo.y);
}
},
/**
* The "refresh" methods informs the ScaleManager that a layout refresh is required.
*
* The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout)
* when the browser is resized, the orientation changes, or when there is a detected change
* of the Parent size. Refreshing is also done automatically when public properties,
* such as {@link #scaleMode}, are updated or state-changing methods are invoked.
*
* The "refresh" method _may_ need to be used in a few (rare) situtations when
*
* - a device change event is not correctly detected; or
* - the Parent size changes (and an immediate reflow is desired); or
* - the ScaleManager state is updated by non-standard means; or
* - certain {@link #compatibility} properties are manually changed.
*
* The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`.
*
* @method Phaser.ScaleManager#refresh
* @public
*/
refresh: function ()
{
this.scrollTop();
this.queueUpdate(true);
},
/**
* Updates the game / canvas position and size.
*
* @method Phaser.ScaleManager#updateLayout
* @private
*/
updateLayout: function ()
{
var scaleMode = this.currentScaleMode;
if (scaleMode === Phaser.ScaleManager.RESIZE)
{
this.reflowGame();
return;
}
this.scrollTop();
if (this.compatibility.forceMinimumDocumentHeight)
{
/*
* (This came from older code, by why is it here?)
* Set minimum height of content to new window height
*/
document.documentElement.style.minHeight = window.innerHeight + 'px';
}
if (this.incorrectOrientation)
{
this.setMaximum();
}
else
if (scaleMode === Phaser.ScaleManager.EXACT_FIT)
{
this.setExactFit();
}
else if (scaleMode === Phaser.ScaleManager.SHOW_ALL)
{
if (!this.isFullScreen && this.boundingParent &&
this.compatibility.canExpandParent)
{
/*
* Try to expand parent out, but choosing maximizing dimensions.
* Then select minimize dimensions which should then honor parent
* maximum bound applications.
*/
this.setShowAll(true);
this.resetCanvas();
this.setShowAll();
}
else
{
this.setShowAll();
}
}
else if (scaleMode === Phaser.ScaleManager.NO_SCALE)
{
this.width = this.game.width;
this.height = this.game.height;
}
else if (scaleMode === Phaser.ScaleManager.USER_SCALE)
{
this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x;
this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y;
}
if (!this.compatibility.canExpandParent &&
(scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE))
{
var bounds = this.getParentBounds(this._tempBounds);
this.width = Math.min(this.width, bounds.width);
this.height = Math.min(this.height, bounds.height);
}
// Always truncate / force to integer
this.width = this.width | 0;
this.height = this.height | 0;
this.reflowCanvas();
},
/**
* Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill.
*
* If in fullscreen mode or without parent (see {@link #parentI