diff --git a/docs/EaselJS_docs-0.8.1.zip b/docs/EaselJS_docs-0.8.1.zip index d0bfe518c..b16d203fb 100644 Binary files a/docs/EaselJS_docs-0.8.1.zip and b/docs/EaselJS_docs-0.8.1.zip differ diff --git a/ellipticalArcDemo.htm b/ellipticalArcDemo.htm new file mode 100644 index 000000000..cc9fba880 --- /dev/null +++ b/ellipticalArcDemo.htm @@ -0,0 +1,99 @@ + + + + + + diff --git a/lib/easeljs-0.8.1.combined.js b/lib/easeljs-0.8.1.combined.js index d32fd5c64..1fd048864 100644 --- a/lib/easeljs-0.8.1.combined.js +++ b/lib/easeljs-0.8.1.combined.js @@ -1,385 +1,385 @@ -/*! -* EaselJS -* Visit http://createjs.com/ for documentation, updates and examples. -* -* Copyright (c) 2010 gskinner.com, inc. -* -* Permission is hereby granted, free of charge, to any person -* obtaining a copy of this software and associated documentation -* files (the "Software"), to deal in the Software without -* restriction, including without limitation the rights to use, -* copy, modify, merge, publish, distribute, sublicense, and/or sell -* copies of the Software, and to permit persons to whom the -* Software is furnished to do so, subject to the following -* conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -* OTHER DEALINGS IN THE SOFTWARE. -*/ +/*! +* EaselJS +* Visit http://createjs.com/ for documentation, updates and examples. +* +* Copyright (c) 2010 gskinner.com, inc. +* +* Permission is hereby granted, free of charge, to any person +* obtaining a copy of this software and associated documentation +* files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, +* copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following +* conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +*/ //############################################################################## // extend.js //############################################################################## -this.createjs = this.createjs||{}; - -/** - * @class Utility Methods - */ - -/** - * Sets up the prototype chain and constructor property for a new class. - * - * This should be called right after creating the class constructor. - * - * function MySubClass() {} - * createjs.extend(MySubClass, MySuperClass); - * ClassB.prototype.doSomething = function() { } - * - * var foo = new MySubClass(); - * console.log(foo instanceof MySuperClass); // true - * console.log(foo.prototype.constructor === MySubClass); // true - * - * @method extend - * @param {Function} subclass The subclass. - * @param {Function} superclass The superclass to extend. - * @return {Function} Returns the subclass's new prototype. - */ -createjs.extend = function(subclass, superclass) { - "use strict"; - - function o() { this.constructor = subclass; } - o.prototype = superclass.prototype; - return (subclass.prototype = new o()); +this.createjs = this.createjs||{}; + +/** + * @class Utility Methods + */ + +/** + * Sets up the prototype chain and constructor property for a new class. + * + * This should be called right after creating the class constructor. + * + * function MySubClass() {} + * createjs.extend(MySubClass, MySuperClass); + * MySubClass.prototype.doSomething = function() { } + * + * var foo = new MySubClass(); + * console.log(foo instanceof MySuperClass); // true + * console.log(foo.prototype.constructor === MySubClass); // true + * + * @method extend + * @param {Function} subclass The subclass. + * @param {Function} superclass The superclass to extend. + * @return {Function} Returns the subclass's new prototype. + */ +createjs.extend = function(subclass, superclass) { + "use strict"; + + function o() { this.constructor = subclass; } + o.prototype = superclass.prototype; + return (subclass.prototype = new o()); }; //############################################################################## // promote.js //############################################################################## -this.createjs = this.createjs||{}; - -/** - * @class Utility Methods - */ - -/** - * Promotes any methods on the super class that were overridden, by creating an alias in the format `prefix_methodName`. - * It is recommended to use the super class's name as the prefix. - * An alias to the super class's constructor is always added in the format `prefix_constructor`. - * This allows the subclass to call super class methods without using `function.call`, providing better performance. - * - * For example, if `MySubClass` extends `MySuperClass`, and both define a `draw` method, then calling `promote(MySubClass, "MySuperClass")` - * would add a `MySuperClass_constructor` method to MySubClass and promote the `draw` method on `MySuperClass` to the - * prototype of `MySubClass` as `MySuperClass_draw`. - * - * This should be called after the class's prototype is fully defined. - * - * function ClassA(name) { - * this.name = name; - * } - * ClassA.prototype.greet = function() { - * return "Hello "+this.name; - * } - * - * function ClassB(name, punctuation) { - * this.ClassA_constructor(name); - * this.punctuation = punctuation; - * } - * createjs.extend(ClassB, ClassA); - * ClassB.prototype.greet = function() { - * return this.ClassA_greet()+this.punctuation; - * } - * createjs.promote(ClassB, "ClassA"); - * - * var foo = new ClassB("World", "!?!"); - * console.log(foo.greet()); // Hello World!?! - * - * @method promote - * @param {Function} subclass The class to promote super class methods on. - * @param {String} prefix The prefix to add to the promoted method names. Usually the name of the superclass. - * @return {Function} Returns the subclass. - */ -createjs.promote = function(subclass, prefix) { - "use strict"; - - var subP = subclass.prototype, supP = (Object.getPrototypeOf&&Object.getPrototypeOf(subP))||subP.__proto__; - if (supP) { - subP[(prefix+="_") + "constructor"] = supP.constructor; // constructor is not always innumerable - for (var n in supP) { - if (subP.hasOwnProperty(n) && (typeof supP[n] == "function")) { subP[prefix + n] = supP[n]; } - } - } - return subclass; +this.createjs = this.createjs||{}; + +/** + * @class Utility Methods + */ + +/** + * Promotes any methods on the super class that were overridden, by creating an alias in the format `prefix_methodName`. + * It is recommended to use the super class's name as the prefix. + * An alias to the super class's constructor is always added in the format `prefix_constructor`. + * This allows the subclass to call super class methods without using `function.call`, providing better performance. + * + * For example, if `MySubClass` extends `MySuperClass`, and both define a `draw` method, then calling `promote(MySubClass, "MySuperClass")` + * would add a `MySuperClass_constructor` method to MySubClass and promote the `draw` method on `MySuperClass` to the + * prototype of `MySubClass` as `MySuperClass_draw`. + * + * This should be called after the class's prototype is fully defined. + * + * function ClassA(name) { + * this.name = name; + * } + * ClassA.prototype.greet = function() { + * return "Hello "+this.name; + * } + * + * function ClassB(name, punctuation) { + * this.ClassA_constructor(name); + * this.punctuation = punctuation; + * } + * createjs.extend(ClassB, ClassA); + * ClassB.prototype.greet = function() { + * return this.ClassA_greet()+this.punctuation; + * } + * createjs.promote(ClassB, "ClassA"); + * + * var foo = new ClassB("World", "!?!"); + * console.log(foo.greet()); // Hello World!?! + * + * @method promote + * @param {Function} subclass The class to promote super class methods on. + * @param {String} prefix The prefix to add to the promoted method names. Usually the name of the superclass. + * @return {Function} Returns the subclass. + */ +createjs.promote = function(subclass, prefix) { + "use strict"; + + var subP = subclass.prototype, supP = (Object.getPrototypeOf&&Object.getPrototypeOf(subP))||subP.__proto__; + if (supP) { + subP[(prefix+="_") + "constructor"] = supP.constructor; // constructor is not always innumerable + for (var n in supP) { + if (subP.hasOwnProperty(n) && (typeof supP[n] == "function")) { subP[prefix + n] = supP[n]; } + } + } + return subclass; }; //############################################################################## // indexOf.js //############################################################################## -this.createjs = this.createjs||{}; - -/** - * @class Utility Methods - */ - -/** - * Finds the first occurrence of a specified value searchElement in the passed in array, and returns the index of - * that value. Returns -1 if value is not found. - * - * var i = createjs.indexOf(myArray, myElementToFind); - * - * @method indexOf - * @param {Array} array Array to search for searchElement - * @param searchElement Element to find in array. - * @return {Number} The first index of searchElement in array. - */ -createjs.indexOf = function (array, searchElement){ - "use strict"; - - for (var i = 0,l=array.length; i < l; i++) { - if (searchElement === array[i]) { - return i; - } - } - return -1; +this.createjs = this.createjs||{}; + +/** + * @class Utility Methods + */ + +/** + * Finds the first occurrence of a specified value searchElement in the passed in array, and returns the index of + * that value. Returns -1 if value is not found. + * + * var i = createjs.indexOf(myArray, myElementToFind); + * + * @method indexOf + * @param {Array} array Array to search for searchElement + * @param searchElement Element to find in array. + * @return {Number} The first index of searchElement in array. + */ +createjs.indexOf = function (array, searchElement){ + "use strict"; + + for (var i = 0,l=array.length; i < l; i++) { + if (searchElement === array[i]) { + return i; + } + } + return -1; }; //############################################################################## // Event.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - -// constructor: - /** - * Contains properties and methods shared by all events for use with - * {{#crossLink "EventDispatcher"}}{{/crossLink}}. - * - * Note that Event objects are often reused, so you should never - * rely on an event object's state outside of the call stack it was received in. - * @class Event - * @param {String} type The event type. - * @param {Boolean} bubbles Indicates whether the event will bubble through the display list. - * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled. - * @constructor - **/ - function Event(type, bubbles, cancelable) { - - - // public properties: - /** - * The type of event. - * @property type - * @type String - **/ - this.type = type; - - /** - * The object that generated an event. - * @property target - * @type Object - * @default null - * @readonly - */ - this.target = null; - - /** - * The current target that a bubbling event is being dispatched from. For non-bubbling events, this will - * always be the same as target. For example, if childObj.parent = parentObj, and a bubbling event - * is generated from childObj, then a listener on parentObj would receive the event with - * target=childObj (the original target) and currentTarget=parentObj (where the listener was added). - * @property currentTarget - * @type Object - * @default null - * @readonly - */ - this.currentTarget = null; - - /** - * For bubbling events, this indicates the current event phase:
    - *
  1. capture phase: starting from the top parent to the target
  2. - *
  3. at target phase: currently being dispatched from the target
  4. - *
  5. bubbling phase: from the target to the top parent
  6. - *
- * @property eventPhase - * @type Number - * @default 0 - * @readonly - */ - this.eventPhase = 0; - - /** - * Indicates whether the event will bubble through the display list. - * @property bubbles - * @type Boolean - * @default false - * @readonly - */ - this.bubbles = !!bubbles; - - /** - * Indicates whether the default behaviour of this event can be cancelled via - * {{#crossLink "Event/preventDefault"}}{{/crossLink}}. This is set via the Event constructor. - * @property cancelable - * @type Boolean - * @default false - * @readonly - */ - this.cancelable = !!cancelable; - - /** - * The epoch time at which this event was created. - * @property timeStamp - * @type Number - * @default 0 - * @readonly - */ - this.timeStamp = (new Date()).getTime(); - - /** - * Indicates if {{#crossLink "Event/preventDefault"}}{{/crossLink}} has been called - * on this event. - * @property defaultPrevented - * @type Boolean - * @default false - * @readonly - */ - this.defaultPrevented = false; - - /** - * Indicates if {{#crossLink "Event/stopPropagation"}}{{/crossLink}} or - * {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called on this event. - * @property propagationStopped - * @type Boolean - * @default false - * @readonly - */ - this.propagationStopped = false; - - /** - * Indicates if {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called - * on this event. - * @property immediatePropagationStopped - * @type Boolean - * @default false - * @readonly - */ - this.immediatePropagationStopped = false; - - /** - * Indicates if {{#crossLink "Event/remove"}}{{/crossLink}} has been called on this event. - * @property removed - * @type Boolean - * @default false - * @readonly - */ - this.removed = false; - } - var p = Event.prototype; - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - -// public methods: - /** - * Sets {{#crossLink "Event/defaultPrevented"}}{{/crossLink}} to true if the event is cancelable. - * Mirrors the DOM level 2 event standard. In general, cancelable events that have `preventDefault()` called will - * cancel the default behaviour associated with the event. - * @method preventDefault - **/ - p.preventDefault = function() { - this.defaultPrevented = this.cancelable&&true; - }; - - /** - * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} to true. - * Mirrors the DOM event standard. - * @method stopPropagation - **/ - p.stopPropagation = function() { - this.propagationStopped = true; - }; - - /** - * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} and - * {{#crossLink "Event/immediatePropagationStopped"}}{{/crossLink}} to true. - * Mirrors the DOM event standard. - * @method stopImmediatePropagation - **/ - p.stopImmediatePropagation = function() { - this.immediatePropagationStopped = this.propagationStopped = true; - }; - - /** - * Causes the active listener to be removed via removeEventListener(); - * - * myBtn.addEventListener("click", function(evt) { - * // do stuff... - * evt.remove(); // removes this listener. - * }); - * - * @method remove - **/ - p.remove = function() { - this.removed = true; - }; - - /** - * Returns a clone of the Event instance. - * @method clone - * @return {Event} a clone of the Event instance. - **/ - p.clone = function() { - return new Event(this.type, this.bubbles, this.cancelable); - }; - - /** - * Provides a chainable shortcut method for setting a number of properties on the instance. - * - * @method set - * @param {Object} props A generic object containing properties to copy to the instance. - * @return {Event} Returns the instance the method is called on (useful for chaining calls.) - * @chainable - */ - p.set = function(props) { - for (var n in props) { this[n] = props[n]; } - return this; - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Event (type="+this.type+")]"; - }; - - createjs.Event = Event; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + +// constructor: + /** + * Contains properties and methods shared by all events for use with + * {{#crossLink "EventDispatcher"}}{{/crossLink}}. + * + * Note that Event objects are often reused, so you should never + * rely on an event object's state outside of the call stack it was received in. + * @class Event + * @param {String} type The event type. + * @param {Boolean} bubbles Indicates whether the event will bubble through the display list. + * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled. + * @constructor + **/ + function Event(type, bubbles, cancelable) { + + + // public properties: + /** + * The type of event. + * @property type + * @type String + **/ + this.type = type; + + /** + * The object that generated an event. + * @property target + * @type Object + * @default null + * @readonly + */ + this.target = null; + + /** + * The current target that a bubbling event is being dispatched from. For non-bubbling events, this will + * always be the same as target. For example, if childObj.parent = parentObj, and a bubbling event + * is generated from childObj, then a listener on parentObj would receive the event with + * target=childObj (the original target) and currentTarget=parentObj (where the listener was added). + * @property currentTarget + * @type Object + * @default null + * @readonly + */ + this.currentTarget = null; + + /** + * For bubbling events, this indicates the current event phase:
    + *
  1. capture phase: starting from the top parent to the target
  2. + *
  3. at target phase: currently being dispatched from the target
  4. + *
  5. bubbling phase: from the target to the top parent
  6. + *
+ * @property eventPhase + * @type Number + * @default 0 + * @readonly + */ + this.eventPhase = 0; + + /** + * Indicates whether the event will bubble through the display list. + * @property bubbles + * @type Boolean + * @default false + * @readonly + */ + this.bubbles = !!bubbles; + + /** + * Indicates whether the default behaviour of this event can be cancelled via + * {{#crossLink "Event/preventDefault"}}{{/crossLink}}. This is set via the Event constructor. + * @property cancelable + * @type Boolean + * @default false + * @readonly + */ + this.cancelable = !!cancelable; + + /** + * The epoch time at which this event was created. + * @property timeStamp + * @type Number + * @default 0 + * @readonly + */ + this.timeStamp = (new Date()).getTime(); + + /** + * Indicates if {{#crossLink "Event/preventDefault"}}{{/crossLink}} has been called + * on this event. + * @property defaultPrevented + * @type Boolean + * @default false + * @readonly + */ + this.defaultPrevented = false; + + /** + * Indicates if {{#crossLink "Event/stopPropagation"}}{{/crossLink}} or + * {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called on this event. + * @property propagationStopped + * @type Boolean + * @default false + * @readonly + */ + this.propagationStopped = false; + + /** + * Indicates if {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called + * on this event. + * @property immediatePropagationStopped + * @type Boolean + * @default false + * @readonly + */ + this.immediatePropagationStopped = false; + + /** + * Indicates if {{#crossLink "Event/remove"}}{{/crossLink}} has been called on this event. + * @property removed + * @type Boolean + * @default false + * @readonly + */ + this.removed = false; + } + var p = Event.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + +// public methods: + /** + * Sets {{#crossLink "Event/defaultPrevented"}}{{/crossLink}} to true if the event is cancelable. + * Mirrors the DOM level 2 event standard. In general, cancelable events that have `preventDefault()` called will + * cancel the default behaviour associated with the event. + * @method preventDefault + **/ + p.preventDefault = function() { + this.defaultPrevented = this.cancelable&&true; + }; + + /** + * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} to true. + * Mirrors the DOM event standard. + * @method stopPropagation + **/ + p.stopPropagation = function() { + this.propagationStopped = true; + }; + + /** + * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} and + * {{#crossLink "Event/immediatePropagationStopped"}}{{/crossLink}} to true. + * Mirrors the DOM event standard. + * @method stopImmediatePropagation + **/ + p.stopImmediatePropagation = function() { + this.immediatePropagationStopped = this.propagationStopped = true; + }; + + /** + * Causes the active listener to be removed via removeEventListener(); + * + * myBtn.addEventListener("click", function(evt) { + * // do stuff... + * evt.remove(); // removes this listener. + * }); + * + * @method remove + **/ + p.remove = function() { + this.removed = true; + }; + + /** + * Returns a clone of the Event instance. + * @method clone + * @return {Event} a clone of the Event instance. + **/ + p.clone = function() { + return new Event(this.type, this.bubbles, this.cancelable); + }; + + /** + * Provides a chainable shortcut method for setting a number of properties on the instance. + * + * @method set + * @param {Object} props A generic object containing properties to copy to the instance. + * @return {Event} Returns the instance the method is called on (useful for chaining calls.) + * @chainable + */ + p.set = function(props) { + for (var n in props) { this[n] = props[n]; } + return this; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Event (type="+this.type+")]"; + }; + + createjs.Event = Event; }()); //############################################################################## @@ -436,7 +436,12 @@ this.createjs = this.createjs||{}; * console.log(instance == this); // true, "on" uses dispatcher scope by default. * }); * - * If you want to use addEventListener instead, you may want to use function.bind() or a similar proxy to manage scope. + * If you want to use addEventListener instead, you may want to use function.bind() or a similar proxy to manage + * scope. + * + * Browser support + * The event model in CreateJS can be used separately from the suite in any project, however the inheritance model + * requires modern browsers (IE9+). * * * @class EventDispatcher @@ -777,6115 +782,9256 @@ this.createjs = this.createjs||{}; // Ticker.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * The Ticker provides a centralized tick or heartbeat broadcast at a set interval. Listeners can subscribe to the tick - * event to be notified when a set time interval has elapsed. - * - * Note that the interval that the tick event is called is a target interval, and may be broadcast at a slower interval - * when under high CPU load. The Ticker class uses a static interface (ex. `Ticker.framerate = 30;`) and - * can not be instantiated. - * - *

Example

- * - * createjs.Ticker.addEventListener("tick", handleTick); - * function handleTick(event) { - * // Actions carried out each tick (aka frame) - * if (!event.paused) { - * // Actions carried out when the Ticker is not paused. - * } - * } - * - * @class Ticker - * @uses EventDispatcher - * @static - **/ - function Ticker() { - throw "Ticker cannot be instantiated."; - } - - -// constants: - /** - * In this mode, Ticker uses the requestAnimationFrame API, but attempts to synch the ticks to target framerate. It - * uses a simple heuristic that compares the time of the RAF return to the target time for the current frame and - * dispatches the tick when the time is within a certain threshold. - * - * This mode has a higher variance for time between frames than {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}}, - * but does not require that content be time based as with {{#crossLink "Ticker/RAF:property"}}{{/crossLink}} while - * gaining the benefits of that API (screen synch, background throttling). - * - * Variance is usually lowest for framerates that are a divisor of the RAF frequency. This is usually 60, so - * framerates of 10, 12, 15, 20, and 30 work well. - * - * Falls back to {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}} if the requestAnimationFrame API is not - * supported. - * @property RAF_SYNCHED - * @static - * @type {String} - * @default "synched" - * @readonly - **/ - Ticker.RAF_SYNCHED = "synched"; - - /** - * In this mode, Ticker passes through the requestAnimationFrame heartbeat, ignoring the target framerate completely. - * Because requestAnimationFrame frequency is not deterministic, any content using this mode should be time based. - * You can leverage {{#crossLink "Ticker/getTime"}}{{/crossLink}} and the {{#crossLink "Ticker/tick:event"}}{{/crossLink}} - * event object's "delta" properties to make this easier. - * - * Falls back on {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}} if the requestAnimationFrame API is not - * supported. - * @property RAF - * @static - * @type {String} - * @default "raf" - * @readonly - **/ - Ticker.RAF = "raf"; - - /** - * In this mode, Ticker uses the setTimeout API. This provides predictable, adaptive frame timing, but does not - * provide the benefits of requestAnimationFrame (screen synch, background throttling). - * @property TIMEOUT - * @static - * @type {String} - * @default "timeout" - * @readonly - **/ - Ticker.TIMEOUT = "timeout"; - - -// static events: - /** - * Dispatched each tick. The event will be dispatched to each listener even when the Ticker has been paused using - * {{#crossLink "Ticker/setPaused"}}{{/crossLink}}. - * - *

Example

- * - * createjs.Ticker.addEventListener("tick", handleTick); - * function handleTick(event) { - * console.log("Paused:", event.paused, event.delta); - * } - * - * @event tick - * @param {Object} target The object that dispatched the event. - * @param {String} type The event type. - * @param {Boolean} paused Indicates whether the ticker is currently paused. - * @param {Number} delta The time elapsed in ms since the last tick. - * @param {Number} time The total time in ms since Ticker was initialized. - * @param {Number} runTime The total time in ms that Ticker was not paused since it was initialized. For example, - * you could determine the amount of time that the Ticker has been paused since initialization with `time-runTime`. - * @since 0.6.0 - */ - - -// public static properties: - /** - * Deprecated in favour of {{#crossLink "Ticker/timingMode"}}{{/crossLink}}, and will be removed in a future version. If true, timingMode will - * use {{#crossLink "Ticker/RAF_SYNCHED"}}{{/crossLink}} by default. - * @deprecated Deprecated in favour of {{#crossLink "Ticker/timingMode"}}{{/crossLink}}. - * @property useRAF - * @static - * @type {Boolean} - * @default false - **/ - Ticker.useRAF = false; - - /** - * Specifies the timing api (setTimeout or requestAnimationFrame) and mode to use. See - * {{#crossLink "Ticker/TIMEOUT"}}{{/crossLink}}, {{#crossLink "Ticker/RAF"}}{{/crossLink}}, and - * {{#crossLink "Ticker/RAF_SYNCHED"}}{{/crossLink}} for mode details. - * @property timingMode - * @static - * @type {String} - * @default Ticker.TIMEOUT - **/ - Ticker.timingMode = null; - - /** - * Specifies a maximum value for the delta property in the tick event object. This is useful when building time - * based animations and systems to prevent issues caused by large time gaps caused by background tabs, system sleep, - * alert dialogs, or other blocking routines. Double the expected frame duration is often an effective value - * (ex. maxDelta=50 when running at 40fps). - * - * This does not impact any other values (ex. time, runTime, etc), so you may experience issues if you enable maxDelta - * when using both delta and other values. - * - * If 0, there is no maximum. - * @property maxDelta - * @static - * @type {number} - * @default 0 - */ - Ticker.maxDelta = 0; - - /** - * When the ticker is paused, all listeners will still receive a tick event, but the paused property - * of the event will be `true`. Also, while paused the `runTime` will not increase. See {{#crossLink "Ticker/tick:event"}}{{/crossLink}}, - * {{#crossLink "Ticker/getTime"}}{{/crossLink}}, and {{#crossLink "Ticker/getEventTime"}}{{/crossLink}} for more - * info. - * - *

Example

- * - * createjs.Ticker.addEventListener("tick", handleTick); - * createjs.Ticker.paused = true; - * function handleTick(event) { - * console.log(event.paused, - * createjs.Ticker.getTime(false), - * createjs.Ticker.getTime(true)); - * } - * - * @property paused - * @static - * @type {Boolean} - * @default false - **/ - Ticker.paused = false; - - -// mix-ins: - // EventDispatcher methods: - Ticker.removeEventListener = null; - Ticker.removeAllEventListeners = null; - Ticker.dispatchEvent = null; - Ticker.hasEventListener = null; - Ticker._listeners = null; - createjs.EventDispatcher.initialize(Ticker); // inject EventDispatcher methods. - Ticker._addEventListener = Ticker.addEventListener; - Ticker.addEventListener = function() { - !Ticker._inited&&Ticker.init(); - return Ticker._addEventListener.apply(Ticker, arguments); - }; - - -// private static properties: - /** - * @property _inited - * @static - * @type {Boolean} - * @protected - **/ - Ticker._inited = false; - - /** - * @property _startTime - * @static - * @type {Number} - * @protected - **/ - Ticker._startTime = 0; - - /** - * @property _pausedTime - * @static - * @type {Number} - * @protected - **/ - Ticker._pausedTime=0; - - /** - * The number of ticks that have passed - * @property _ticks - * @static - * @type {Number} - * @protected - **/ - Ticker._ticks = 0; - - /** - * The number of ticks that have passed while Ticker has been paused - * @property _pausedTicks - * @static - * @type {Number} - * @protected - **/ - Ticker._pausedTicks = 0; - - /** - * @property _interval - * @static - * @type {Number} - * @protected - **/ - Ticker._interval = 50; - - /** - * @property _lastTime - * @static - * @type {Number} - * @protected - **/ - Ticker._lastTime = 0; - - /** - * @property _times - * @static - * @type {Array} - * @protected - **/ - Ticker._times = null; - - /** - * @property _tickTimes - * @static - * @type {Array} - * @protected - **/ - Ticker._tickTimes = null; - - /** - * Stores the timeout or requestAnimationFrame id. - * @property _timerId - * @static - * @type {Number} - * @protected - **/ - Ticker._timerId = null; - - /** - * True if currently using requestAnimationFrame, false if using setTimeout. This may be different than timingMode - * if that property changed and a tick hasn't fired. - * @property _raf - * @static - * @type {Boolean} - * @protected - **/ - Ticker._raf = true; - - -// static getter / setters: - /** - * Use the {{#crossLink "Ticker/interval:property"}}{{/crossLink}} property instead. - * @method setInterval - * @static - * @param {Number} interval - * @deprecated - **/ - Ticker.setInterval = function(interval) { - Ticker._interval = interval; - if (!Ticker._inited) { return; } - Ticker._setupTick(); - }; - - /** - * Use the {{#crossLink "Ticker/interval:property"}}{{/crossLink}} property instead. - * @method getInterval - * @static - * @return {Number} - * @deprecated - **/ - Ticker.getInterval = function() { - return Ticker._interval; - }; - - /** - * Use the {{#crossLink "Ticker/framerate:property"}}{{/crossLink}} property instead. - * @method setFPS - * @static - * @param {Number} value - * @deprecated - **/ - Ticker.setFPS = function(value) { - Ticker.setInterval(1000/value); - }; - - /** - * Use the {{#crossLink "Ticker/framerate:property"}}{{/crossLink}} property instead. - * @method getFPS - * @static - * @return {Number} - * @deprecated - **/ - Ticker.getFPS = function() { - return 1000/Ticker._interval; - }; - - /** - * Indicates the target time (in milliseconds) between ticks. Default is 50 (20 FPS). - * Note that actual time between ticks may be more than specified depending on CPU load. - * This property is ignored if the ticker is using the `RAF` timing mode. - * @property interval - * @static - * @type {Number} - **/ - - /** - * Indicates the target frame rate in frames per second (FPS). Effectively just a shortcut to `interval`, where - * `framerate == 1000/interval`. - * @property framerate - * @static - * @type {Number} - **/ - try { - Object.defineProperties(Ticker, { - interval: { get: Ticker.getInterval, set: Ticker.setInterval }, - framerate: { get: Ticker.getFPS, set: Ticker.setFPS } - }); - } catch (e) { console.log(e); } - - -// public static methods: - /** - * Starts the tick. This is called automatically when the first listener is added. - * @method init - * @static - **/ - Ticker.init = function() { - if (Ticker._inited) { return; } - Ticker._inited = true; - Ticker._times = []; - Ticker._tickTimes = []; - Ticker._startTime = Ticker._getTime(); - Ticker._times.push(Ticker._lastTime = 0); - Ticker.interval = Ticker._interval; - }; - - /** - * Stops the Ticker and removes all listeners. Use init() to restart the Ticker. - * @method reset - * @static - **/ - Ticker.reset = function() { - if (Ticker._raf) { - var f = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || window.msCancelAnimationFrame; - f&&f(Ticker._timerId); - } else { - clearTimeout(Ticker._timerId); - } - Ticker.removeAllEventListeners("tick"); - Ticker._timerId = Ticker._times = Ticker._tickTimes = null; - Ticker._startTime = Ticker._lastTime = Ticker._ticks = 0; - Ticker._inited = false; - }; - - /** - * Returns the average time spent within a tick. This can vary significantly from the value provided by getMeasuredFPS - * because it only measures the time spent within the tick execution stack. - * - * Example 1: With a target FPS of 20, getMeasuredFPS() returns 20fps, which indicates an average of 50ms between - * the end of one tick and the end of the next. However, getMeasuredTickTime() returns 15ms. This indicates that - * there may be up to 35ms of "idle" time between the end of one tick and the start of the next. - * - * Example 2: With a target FPS of 30, getFPS() returns 10fps, which indicates an average of 100ms between the end of - * one tick and the end of the next. However, getMeasuredTickTime() returns 20ms. This would indicate that something - * other than the tick is using ~80ms (another script, DOM rendering, etc). - * @method getMeasuredTickTime - * @static - * @param {Number} [ticks] The number of previous ticks over which to measure the average time spent in a tick. - * Defaults to the number of ticks per second. To get only the last tick's time, pass in 1. - * @return {Number} The average time spent in a tick in milliseconds. - **/ - Ticker.getMeasuredTickTime = function(ticks) { - var ttl=0, times=Ticker._tickTimes; - if (!times || times.length < 1) { return -1; } - - // by default, calculate average for the past ~1 second: - ticks = Math.min(times.length, ticks||(Ticker.getFPS()|0)); - for (var i=0; i= (Ticker._interval-1)*0.97) { - Ticker._tick(); - } - }; - - /** - * @method _handleRAF - * @static - * @protected - **/ - Ticker._handleRAF = function() { - Ticker._timerId = null; - Ticker._setupTick(); - Ticker._tick(); - }; - - /** - * @method _handleTimeout - * @static - * @protected - **/ - Ticker._handleTimeout = function() { - Ticker._timerId = null; - Ticker._setupTick(); - Ticker._tick(); - }; - - /** - * @method _setupTick - * @static - * @protected - **/ - Ticker._setupTick = function() { - if (Ticker._timerId != null) { return; } // avoid duplicates - - var mode = Ticker.timingMode||(Ticker.useRAF&&Ticker.RAF_SYNCHED); - if (mode == Ticker.RAF_SYNCHED || mode == Ticker.RAF) { - var f = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; - if (f) { - Ticker._timerId = f(mode == Ticker.RAF ? Ticker._handleRAF : Ticker._handleSynch); - Ticker._raf = true; - return; - } - } - Ticker._raf = false; - Ticker._timerId = setTimeout(Ticker._handleTimeout, Ticker._interval); - }; - - /** - * @method _tick - * @static - * @protected - **/ - Ticker._tick = function() { - var paused = Ticker.paused; - var time = Ticker._getTime(); - var elapsedTime = time-Ticker._lastTime; - Ticker._lastTime = time; - Ticker._ticks++; - - if (paused) { - Ticker._pausedTicks++; - Ticker._pausedTime += elapsedTime; - } - - if (Ticker.hasEventListener("tick")) { - var event = new createjs.Event("tick"); - var maxDelta = Ticker.maxDelta; - event.delta = (maxDelta && elapsedTime > maxDelta) ? maxDelta : elapsedTime; - event.paused = paused; - event.time = time; - event.runTime = time-Ticker._pausedTime; - Ticker.dispatchEvent(event); - } - - Ticker._tickTimes.unshift(Ticker._getTime()-time); - while (Ticker._tickTimes.length > 100) { Ticker._tickTimes.pop(); } - - Ticker._times.unshift(time); - while (Ticker._times.length > 100) { Ticker._times.pop(); } - }; - - /** - * @method _getTime - * @static - * @protected - **/ - var now = window.performance && (performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow); - Ticker._getTime = function() { - return ((now&&now.call(performance))||(new Date().getTime())) - Ticker._startTime; - }; - - - createjs.Ticker = Ticker; -}()); - -//############################################################################## -// UID.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Global utility for generating sequential unique ID numbers. The UID class uses a static interface (ex. UID.get()) - * and should not be instantiated. - * @class UID - * @static - **/ - function UID() { - throw "UID cannot be instantiated"; - } - - -// private static properties: - /** - * @property _nextID - * @type Number - * @protected - **/ - UID._nextID = 0; - - -// public static methods: - /** - * Returns the next unique id. - * @method get - * @return {Number} The next unique id - * @static - **/ - UID.get = function() { - return UID._nextID++; - }; - - - createjs.UID = UID; -}()); - -//############################################################################## -// MouseEvent.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Passed as the parameter to all mouse/pointer/touch related events. For a listing of mouse events and their properties, - * see the {{#crossLink "DisplayObject"}}{{/crossLink}} and {{#crossLink "Stage"}}{{/crossLink}} event listings. - * @class MouseEvent - * @param {String} type The event type. - * @param {Boolean} bubbles Indicates whether the event will bubble through the display list. - * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled. - * @param {Number} stageX The normalized x position relative to the stage. - * @param {Number} stageY The normalized y position relative to the stage. - * @param {MouseEvent} nativeEvent The native DOM event related to this mouse event. - * @param {Number} pointerID The unique id for the pointer. - * @param {Boolean} primary Indicates whether this is the primary pointer in a multitouch environment. - * @param {Number} rawX The raw x position relative to the stage. - * @param {Number} rawY The raw y position relative to the stage. - * @param {DisplayObject} relatedTarget The secondary target for the event. - * @extends Event - * @constructor - **/ - function MouseEvent(type, bubbles, cancelable, stageX, stageY, nativeEvent, pointerID, primary, rawX, rawY, relatedTarget) { - this.Event_constructor(type, bubbles, cancelable); - - - // public properties: - /** - * The normalized x position on the stage. This will always be within the range 0 to stage width. - * @property stageX - * @type Number - */ - this.stageX = stageX; - - /** - * The normalized y position on the stage. This will always be within the range 0 to stage height. - * @property stageY - * @type Number - **/ - this.stageY = stageY; - - /** - * The raw x position relative to the stage. Normally this will be the same as the stageX value, unless - * stage.mouseMoveOutside is true and the pointer is outside of the stage bounds. - * @property rawX - * @type Number - */ - this.rawX = (rawX==null)?stageX:rawX; - - /** - * The raw y position relative to the stage. Normally this will be the same as the stageY value, unless - * stage.mouseMoveOutside is true and the pointer is outside of the stage bounds. - * @property rawY - * @type Number - */ - this.rawY = (rawY==null)?stageY:rawY; - - /** - * The native MouseEvent generated by the browser. The properties and API for this - * event may differ between browsers. This property will be null if the - * EaselJS property was not directly generated from a native MouseEvent. - * @property nativeEvent - * @type HtmlMouseEvent - * @default null - **/ - this.nativeEvent = nativeEvent; - - /** - * The unique id for the pointer (touch point or cursor). This will be either -1 for the mouse, or the system - * supplied id value. - * @property pointerID - * @type {Number} - */ - this.pointerID = pointerID; - - /** - * Indicates whether this is the primary pointer in a multitouch environment. This will always be true for the mouse. - * For touch pointers, the first pointer in the current stack will be considered the primary pointer. - * @property primary - * @type {Boolean} - */ - this.primary = !!primary; - - /** - * The secondary target for the event, if applicable. This is used for mouseout/rollout - * events to indicate the object that the mouse entered from, mouseover/rollover for the object the mouse exited, - * and stagemousedown/stagemouseup events for the object that was the under the cursor, if any. - * - * Only valid interaction targets will be returned (ie. objects with mouse listeners or a cursor set). - * @property relatedTarget - * @type {DisplayObject} - */ - this.relatedTarget = relatedTarget; - } - var p = createjs.extend(MouseEvent, createjs.Event); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// getter / setters: - /** - * Returns the x position of the mouse in the local coordinate system of the current target (ie. the dispatcher). - * @property localX - * @type {Number} - * @readonly - */ - p._get_localX = function() { - return this.currentTarget.globalToLocal(this.rawX, this.rawY).x; - }; - - /** - * Returns the y position of the mouse in the local coordinate system of the current target (ie. the dispatcher). - * @property localY - * @type {Number} - * @readonly - */ - p._get_localY = function() { - return this.currentTarget.globalToLocal(this.rawX, this.rawY).y; - }; - - /** - * Indicates whether the event was generated by a touch input (versus a mouse input). - * @property isTouch - * @type {Boolean} - * @readonly - */ - p._get_isTouch = function() { - return this.pointerID !== -1; - }; - - - try { - Object.defineProperties(p, { - localX: { get: p._get_localX }, - localY: { get: p._get_localY }, - isTouch: { get: p._get_isTouch } - }); - } catch (e) {} // TODO: use Log - +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * The Ticker provides a centralized tick or heartbeat broadcast at a set interval. Listeners can subscribe to the tick + * event to be notified when a set time interval has elapsed. + * + * Note that the interval that the tick event is called is a target interval, and may be broadcast at a slower interval + * when under high CPU load. The Ticker class uses a static interface (ex. `Ticker.framerate = 30;`) and + * can not be instantiated. + * + *

Example

+ * + * createjs.Ticker.addEventListener("tick", handleTick); + * function handleTick(event) { + * // Actions carried out each tick (aka frame) + * if (!event.paused) { + * // Actions carried out when the Ticker is not paused. + * } + * } + * + * @class Ticker + * @uses EventDispatcher + * @static + **/ + function Ticker() { + throw "Ticker cannot be instantiated."; + } + + +// constants: + /** + * In this mode, Ticker uses the requestAnimationFrame API, but attempts to synch the ticks to target framerate. It + * uses a simple heuristic that compares the time of the RAF return to the target time for the current frame and + * dispatches the tick when the time is within a certain threshold. + * + * This mode has a higher variance for time between frames than {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}}, + * but does not require that content be time based as with {{#crossLink "Ticker/RAF:property"}}{{/crossLink}} while + * gaining the benefits of that API (screen synch, background throttling). + * + * Variance is usually lowest for framerates that are a divisor of the RAF frequency. This is usually 60, so + * framerates of 10, 12, 15, 20, and 30 work well. + * + * Falls back to {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}} if the requestAnimationFrame API is not + * supported. + * @property RAF_SYNCHED + * @static + * @type {String} + * @default "synched" + * @readonly + **/ + Ticker.RAF_SYNCHED = "synched"; + + /** + * In this mode, Ticker passes through the requestAnimationFrame heartbeat, ignoring the target framerate completely. + * Because requestAnimationFrame frequency is not deterministic, any content using this mode should be time based. + * You can leverage {{#crossLink "Ticker/getTime"}}{{/crossLink}} and the {{#crossLink "Ticker/tick:event"}}{{/crossLink}} + * event object's "delta" properties to make this easier. + * + * Falls back on {{#crossLink "Ticker/TIMEOUT:property"}}{{/crossLink}} if the requestAnimationFrame API is not + * supported. + * @property RAF + * @static + * @type {String} + * @default "raf" + * @readonly + **/ + Ticker.RAF = "raf"; + + /** + * In this mode, Ticker uses the setTimeout API. This provides predictable, adaptive frame timing, but does not + * provide the benefits of requestAnimationFrame (screen synch, background throttling). + * @property TIMEOUT + * @static + * @type {String} + * @default "timeout" + * @readonly + **/ + Ticker.TIMEOUT = "timeout"; + + +// static events: + /** + * Dispatched each tick. The event will be dispatched to each listener even when the Ticker has been paused using + * {{#crossLink "Ticker/setPaused"}}{{/crossLink}}. + * + *

Example

+ * + * createjs.Ticker.addEventListener("tick", handleTick); + * function handleTick(event) { + * console.log("Paused:", event.paused, event.delta); + * } + * + * @event tick + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @param {Boolean} paused Indicates whether the ticker is currently paused. + * @param {Number} delta The time elapsed in ms since the last tick. + * @param {Number} time The total time in ms since Ticker was initialized. + * @param {Number} runTime The total time in ms that Ticker was not paused since it was initialized. For example, + * you could determine the amount of time that the Ticker has been paused since initialization with `time-runTime`. + * @since 0.6.0 + */ + + +// public static properties: + /** + * Deprecated in favour of {{#crossLink "Ticker/timingMode"}}{{/crossLink}}, and will be removed in a future version. If true, timingMode will + * use {{#crossLink "Ticker/RAF_SYNCHED"}}{{/crossLink}} by default. + * @deprecated Deprecated in favour of {{#crossLink "Ticker/timingMode"}}{{/crossLink}}. + * @property useRAF + * @static + * @type {Boolean} + * @default false + **/ + Ticker.useRAF = false; + + /** + * Specifies the timing api (setTimeout or requestAnimationFrame) and mode to use. See + * {{#crossLink "Ticker/TIMEOUT"}}{{/crossLink}}, {{#crossLink "Ticker/RAF"}}{{/crossLink}}, and + * {{#crossLink "Ticker/RAF_SYNCHED"}}{{/crossLink}} for mode details. + * @property timingMode + * @static + * @type {String} + * @default Ticker.TIMEOUT + **/ + Ticker.timingMode = null; + + /** + * Specifies a maximum value for the delta property in the tick event object. This is useful when building time + * based animations and systems to prevent issues caused by large time gaps caused by background tabs, system sleep, + * alert dialogs, or other blocking routines. Double the expected frame duration is often an effective value + * (ex. maxDelta=50 when running at 40fps). + * + * This does not impact any other values (ex. time, runTime, etc), so you may experience issues if you enable maxDelta + * when using both delta and other values. + * + * If 0, there is no maximum. + * @property maxDelta + * @static + * @type {number} + * @default 0 + */ + Ticker.maxDelta = 0; + + /** + * When the ticker is paused, all listeners will still receive a tick event, but the paused property + * of the event will be `true`. Also, while paused the `runTime` will not increase. See {{#crossLink "Ticker/tick:event"}}{{/crossLink}}, + * {{#crossLink "Ticker/getTime"}}{{/crossLink}}, and {{#crossLink "Ticker/getEventTime"}}{{/crossLink}} for more + * info. + * + *

Example

+ * + * createjs.Ticker.addEventListener("tick", handleTick); + * createjs.Ticker.paused = true; + * function handleTick(event) { + * console.log(event.paused, + * createjs.Ticker.getTime(false), + * createjs.Ticker.getTime(true)); + * } + * + * @property paused + * @static + * @type {Boolean} + * @default false + **/ + Ticker.paused = false; + + +// mix-ins: + // EventDispatcher methods: + Ticker.removeEventListener = null; + Ticker.removeAllEventListeners = null; + Ticker.dispatchEvent = null; + Ticker.hasEventListener = null; + Ticker._listeners = null; + createjs.EventDispatcher.initialize(Ticker); // inject EventDispatcher methods. + Ticker._addEventListener = Ticker.addEventListener; + Ticker.addEventListener = function() { + !Ticker._inited&&Ticker.init(); + return Ticker._addEventListener.apply(Ticker, arguments); + }; + + +// private static properties: + /** + * @property _inited + * @static + * @type {Boolean} + * @protected + **/ + Ticker._inited = false; + + /** + * @property _startTime + * @static + * @type {Number} + * @protected + **/ + Ticker._startTime = 0; + + /** + * @property _pausedTime + * @static + * @type {Number} + * @protected + **/ + Ticker._pausedTime=0; + + /** + * The number of ticks that have passed + * @property _ticks + * @static + * @type {Number} + * @protected + **/ + Ticker._ticks = 0; + + /** + * The number of ticks that have passed while Ticker has been paused + * @property _pausedTicks + * @static + * @type {Number} + * @protected + **/ + Ticker._pausedTicks = 0; + + /** + * @property _interval + * @static + * @type {Number} + * @protected + **/ + Ticker._interval = 50; + + /** + * @property _lastTime + * @static + * @type {Number} + * @protected + **/ + Ticker._lastTime = 0; + + /** + * @property _times + * @static + * @type {Array} + * @protected + **/ + Ticker._times = null; + + /** + * @property _tickTimes + * @static + * @type {Array} + * @protected + **/ + Ticker._tickTimes = null; + + /** + * Stores the timeout or requestAnimationFrame id. + * @property _timerId + * @static + * @type {Number} + * @protected + **/ + Ticker._timerId = null; + + /** + * True if currently using requestAnimationFrame, false if using setTimeout. This may be different than timingMode + * if that property changed and a tick hasn't fired. + * @property _raf + * @static + * @type {Boolean} + * @protected + **/ + Ticker._raf = true; + + +// static getter / setters: + /** + * Use the {{#crossLink "Ticker/interval:property"}}{{/crossLink}} property instead. + * @method setInterval + * @static + * @param {Number} interval + * @deprecated + **/ + Ticker.setInterval = function(interval) { + Ticker._interval = interval; + if (!Ticker._inited) { return; } + Ticker._setupTick(); + }; + + /** + * Use the {{#crossLink "Ticker/interval:property"}}{{/crossLink}} property instead. + * @method getInterval + * @static + * @return {Number} + * @deprecated + **/ + Ticker.getInterval = function() { + return Ticker._interval; + }; + + /** + * Use the {{#crossLink "Ticker/framerate:property"}}{{/crossLink}} property instead. + * @method setFPS + * @static + * @param {Number} value + * @deprecated + **/ + Ticker.setFPS = function(value) { + Ticker.setInterval(1000/value); + }; + + /** + * Use the {{#crossLink "Ticker/framerate:property"}}{{/crossLink}} property instead. + * @method getFPS + * @static + * @return {Number} + * @deprecated + **/ + Ticker.getFPS = function() { + return 1000/Ticker._interval; + }; + + /** + * Indicates the target time (in milliseconds) between ticks. Default is 50 (20 FPS). + * Note that actual time between ticks may be more than specified depending on CPU load. + * This property is ignored if the ticker is using the `RAF` timing mode. + * @property interval + * @static + * @type {Number} + **/ + + /** + * Indicates the target frame rate in frames per second (FPS). Effectively just a shortcut to `interval`, where + * `framerate == 1000/interval`. + * @property framerate + * @static + * @type {Number} + **/ + try { + Object.defineProperties(Ticker, { + interval: { get: Ticker.getInterval, set: Ticker.setInterval }, + framerate: { get: Ticker.getFPS, set: Ticker.setFPS } + }); + } catch (e) { console.log(e); } + + +// public static methods: + /** + * Starts the tick. This is called automatically when the first listener is added. + * @method init + * @static + **/ + Ticker.init = function() { + if (Ticker._inited) { return; } + Ticker._inited = true; + Ticker._times = []; + Ticker._tickTimes = []; + Ticker._startTime = Ticker._getTime(); + Ticker._times.push(Ticker._lastTime = 0); + Ticker.interval = Ticker._interval; + }; + + /** + * Stops the Ticker and removes all listeners. Use init() to restart the Ticker. + * @method reset + * @static + **/ + Ticker.reset = function() { + if (Ticker._raf) { + var f = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || window.msCancelAnimationFrame; + f&&f(Ticker._timerId); + } else { + clearTimeout(Ticker._timerId); + } + Ticker.removeAllEventListeners("tick"); + Ticker._timerId = Ticker._times = Ticker._tickTimes = null; + Ticker._startTime = Ticker._lastTime = Ticker._ticks = 0; + Ticker._inited = false; + }; + + /** + * Returns the average time spent within a tick. This can vary significantly from the value provided by getMeasuredFPS + * because it only measures the time spent within the tick execution stack. + * + * Example 1: With a target FPS of 20, getMeasuredFPS() returns 20fps, which indicates an average of 50ms between + * the end of one tick and the end of the next. However, getMeasuredTickTime() returns 15ms. This indicates that + * there may be up to 35ms of "idle" time between the end of one tick and the start of the next. + * + * Example 2: With a target FPS of 30, getFPS() returns 10fps, which indicates an average of 100ms between the end of + * one tick and the end of the next. However, getMeasuredTickTime() returns 20ms. This would indicate that something + * other than the tick is using ~80ms (another script, DOM rendering, etc). + * @method getMeasuredTickTime + * @static + * @param {Number} [ticks] The number of previous ticks over which to measure the average time spent in a tick. + * Defaults to the number of ticks per second. To get only the last tick's time, pass in 1. + * @return {Number} The average time spent in a tick in milliseconds. + **/ + Ticker.getMeasuredTickTime = function(ticks) { + var ttl=0, times=Ticker._tickTimes; + if (!times || times.length < 1) { return -1; } + + // by default, calculate average for the past ~1 second: + ticks = Math.min(times.length, ticks||(Ticker.getFPS()|0)); + for (var i=0; i= (Ticker._interval-1)*0.97) { + Ticker._tick(); + } + }; + + /** + * @method _handleRAF + * @static + * @protected + **/ + Ticker._handleRAF = function() { + Ticker._timerId = null; + Ticker._setupTick(); + Ticker._tick(); + }; + + /** + * @method _handleTimeout + * @static + * @protected + **/ + Ticker._handleTimeout = function() { + Ticker._timerId = null; + Ticker._setupTick(); + Ticker._tick(); + }; + + /** + * @method _setupTick + * @static + * @protected + **/ + Ticker._setupTick = function() { + if (Ticker._timerId != null) { return; } // avoid duplicates + + var mode = Ticker.timingMode||(Ticker.useRAF&&Ticker.RAF_SYNCHED); + if (mode == Ticker.RAF_SYNCHED || mode == Ticker.RAF) { + var f = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; + if (f) { + Ticker._timerId = f(mode == Ticker.RAF ? Ticker._handleRAF : Ticker._handleSynch); + Ticker._raf = true; + return; + } + } + Ticker._raf = false; + Ticker._timerId = setTimeout(Ticker._handleTimeout, Ticker._interval); + }; + + /** + * @method _tick + * @static + * @protected + **/ + Ticker._tick = function() { + var paused = Ticker.paused; + var time = Ticker._getTime(); + var elapsedTime = time-Ticker._lastTime; + Ticker._lastTime = time; + Ticker._ticks++; + + if (paused) { + Ticker._pausedTicks++; + Ticker._pausedTime += elapsedTime; + } + + if (Ticker.hasEventListener("tick")) { + var event = new createjs.Event("tick"); + var maxDelta = Ticker.maxDelta; + event.delta = (maxDelta && elapsedTime > maxDelta) ? maxDelta : elapsedTime; + event.paused = paused; + event.time = time; + event.runTime = time-Ticker._pausedTime; + Ticker.dispatchEvent(event); + } + + Ticker._tickTimes.unshift(Ticker._getTime()-time); + while (Ticker._tickTimes.length > 100) { Ticker._tickTimes.pop(); } + + Ticker._times.unshift(time); + while (Ticker._times.length > 100) { Ticker._times.pop(); } + }; + + /** + * @method _getTime + * @static + * @protected + **/ + var now = window.performance && (performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow); + Ticker._getTime = function() { + return ((now&&now.call(performance))||(new Date().getTime())) - Ticker._startTime; + }; + + + createjs.Ticker = Ticker; +}()); -// public methods: - /** - * Returns a clone of the MouseEvent instance. - * @method clone - * @return {MouseEvent} a clone of the MouseEvent instance. - **/ - p.clone = function() { - return new MouseEvent(this.type, this.bubbles, this.cancelable, this.stageX, this.stageY, this.nativeEvent, this.pointerID, this.primary, this.rawX, this.rawY); - }; +//############################################################################## +// UID.js +//############################################################################## - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[MouseEvent (type="+this.type+" stageX="+this.stageX+" stageY="+this.stageY+")]"; - }; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Global utility for generating sequential unique ID numbers. The UID class uses a static interface (ex. UID.get()) + * and should not be instantiated. + * @class UID + * @static + **/ + function UID() { + throw "UID cannot be instantiated"; + } + + +// private static properties: + /** + * @property _nextID + * @type Number + * @protected + **/ + UID._nextID = 0; + + +// public static methods: + /** + * Returns the next unique id. + * @method get + * @return {Number} The next unique id + * @static + **/ + UID.get = function() { + return UID._nextID++; + }; + + + createjs.UID = UID; +}()); +//############################################################################## +// MouseEvent.js +//############################################################################## - createjs.MouseEvent = createjs.promote(MouseEvent, "Event"); +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Passed as the parameter to all mouse/pointer/touch related events. For a listing of mouse events and their properties, + * see the {{#crossLink "DisplayObject"}}{{/crossLink}} and {{#crossLink "Stage"}}{{/crossLink}} event listings. + * @class MouseEvent + * @param {String} type The event type. + * @param {Boolean} bubbles Indicates whether the event will bubble through the display list. + * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled. + * @param {Number} stageX The normalized x position relative to the stage. + * @param {Number} stageY The normalized y position relative to the stage. + * @param {MouseEvent} nativeEvent The native DOM event related to this mouse event. + * @param {Number} pointerID The unique id for the pointer. + * @param {Boolean} primary Indicates whether this is the primary pointer in a multitouch environment. + * @param {Number} rawX The raw x position relative to the stage. + * @param {Number} rawY The raw y position relative to the stage. + * @param {DisplayObject} relatedTarget The secondary target for the event. + * @extends Event + * @constructor + **/ + function MouseEvent(type, bubbles, cancelable, stageX, stageY, nativeEvent, pointerID, primary, rawX, rawY, relatedTarget) { + this.Event_constructor(type, bubbles, cancelable); + + + // public properties: + /** + * The normalized x position on the stage. This will always be within the range 0 to stage width. + * @property stageX + * @type Number + */ + this.stageX = stageX; + + /** + * The normalized y position on the stage. This will always be within the range 0 to stage height. + * @property stageY + * @type Number + **/ + this.stageY = stageY; + + /** + * The raw x position relative to the stage. Normally this will be the same as the stageX value, unless + * stage.mouseMoveOutside is true and the pointer is outside of the stage bounds. + * @property rawX + * @type Number + */ + this.rawX = (rawX==null)?stageX:rawX; + + /** + * The raw y position relative to the stage. Normally this will be the same as the stageY value, unless + * stage.mouseMoveOutside is true and the pointer is outside of the stage bounds. + * @property rawY + * @type Number + */ + this.rawY = (rawY==null)?stageY:rawY; + + /** + * The native MouseEvent generated by the browser. The properties and API for this + * event may differ between browsers. This property will be null if the + * EaselJS property was not directly generated from a native MouseEvent. + * @property nativeEvent + * @type HtmlMouseEvent + * @default null + **/ + this.nativeEvent = nativeEvent; + + /** + * The unique id for the pointer (touch point or cursor). This will be either -1 for the mouse, or the system + * supplied id value. + * @property pointerID + * @type {Number} + */ + this.pointerID = pointerID; + + /** + * Indicates whether this is the primary pointer in a multitouch environment. This will always be true for the mouse. + * For touch pointers, the first pointer in the current stack will be considered the primary pointer. + * @property primary + * @type {Boolean} + */ + this.primary = !!primary; + + /** + * The secondary target for the event, if applicable. This is used for mouseout/rollout + * events to indicate the object that the mouse entered from, mouseover/rollover for the object the mouse exited, + * and stagemousedown/stagemouseup events for the object that was the under the cursor, if any. + * + * Only valid interaction targets will be returned (ie. objects with mouse listeners or a cursor set). + * @property relatedTarget + * @type {DisplayObject} + */ + this.relatedTarget = relatedTarget; + } + var p = createjs.extend(MouseEvent, createjs.Event); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// getter / setters: + /** + * Returns the x position of the mouse in the local coordinate system of the current target (ie. the dispatcher). + * @property localX + * @type {Number} + * @readonly + */ + p._get_localX = function() { + return this.currentTarget.globalToLocal(this.rawX, this.rawY).x; + }; + + /** + * Returns the y position of the mouse in the local coordinate system of the current target (ie. the dispatcher). + * @property localY + * @type {Number} + * @readonly + */ + p._get_localY = function() { + return this.currentTarget.globalToLocal(this.rawX, this.rawY).y; + }; + + /** + * Indicates whether the event was generated by a touch input (versus a mouse input). + * @property isTouch + * @type {Boolean} + * @readonly + */ + p._get_isTouch = function() { + return this.pointerID !== -1; + }; + + + try { + Object.defineProperties(p, { + localX: { get: p._get_localX }, + localY: { get: p._get_localY }, + isTouch: { get: p._get_isTouch } + }); + } catch (e) {} // TODO: use Log + + +// public methods: + /** + * Returns a clone of the MouseEvent instance. + * @method clone + * @return {MouseEvent} a clone of the MouseEvent instance. + **/ + p.clone = function() { + return new MouseEvent(this.type, this.bubbles, this.cancelable, this.stageX, this.stageY, this.nativeEvent, this.pointerID, this.primary, this.rawX, this.rawY); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[MouseEvent (type="+this.type+" stageX="+this.stageX+" stageY="+this.stageY+")]"; + }; + + + createjs.MouseEvent = createjs.promote(MouseEvent, "Event"); }()); //############################################################################## // Matrix2D.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Represents an affine transformation matrix, and provides tools for constructing and concatenating matrices. - * - * This matrix can be visualized as: - * - * [ a c tx - * b d ty - * 0 0 1 ] - * - * Note the locations of b and c. - * - * @class Matrix2D - * @param {Number} [a=1] Specifies the a property for the new matrix. - * @param {Number} [b=0] Specifies the b property for the new matrix. - * @param {Number} [c=0] Specifies the c property for the new matrix. - * @param {Number} [d=1] Specifies the d property for the new matrix. - * @param {Number} [tx=0] Specifies the tx property for the new matrix. - * @param {Number} [ty=0] Specifies the ty property for the new matrix. - * @constructor - **/ - function Matrix2D(a, b, c, d, tx, ty) { - this.setValues(a,b,c,d,tx,ty); - - // public properties: - // assigned in the setValues method. - /** - * Position (0, 0) in a 3x3 affine transformation matrix. - * @property a - * @type Number - **/ - - /** - * Position (0, 1) in a 3x3 affine transformation matrix. - * @property b - * @type Number - **/ - - /** - * Position (1, 0) in a 3x3 affine transformation matrix. - * @property c - * @type Number - **/ - - /** - * Position (1, 1) in a 3x3 affine transformation matrix. - * @property d - * @type Number - **/ - - /** - * Position (2, 0) in a 3x3 affine transformation matrix. - * @property tx - * @type Number - **/ - - /** - * Position (2, 1) in a 3x3 affine transformation matrix. - * @property ty - * @type Number - **/ - } - var p = Matrix2D.prototype; - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// constants: - /** - * Multiplier for converting degrees to radians. Used internally by Matrix2D. - * @property DEG_TO_RAD - * @static - * @final - * @type Number - * @readonly - **/ - Matrix2D.DEG_TO_RAD = Math.PI/180; - - -// static public properties: - /** - * An identity matrix, representing a null transformation. - * @property identity - * @static - * @type Matrix2D - * @readonly - **/ - Matrix2D.identity = null; // set at bottom of class definition. - - -// public methods: - /** - * Sets the specified values on this instance. - * @method setValues - * @param {Number} [a=1] Specifies the a property for the new matrix. - * @param {Number} [b=0] Specifies the b property for the new matrix. - * @param {Number} [c=0] Specifies the c property for the new matrix. - * @param {Number} [d=1] Specifies the d property for the new matrix. - * @param {Number} [tx=0] Specifies the tx property for the new matrix. - * @param {Number} [ty=0] Specifies the ty property for the new matrix. - * @return {Matrix2D} This instance. Useful for chaining method calls. - */ - p.setValues = function(a, b, c, d, tx, ty) { - // don't forget to update docs in the constructor if these change: - this.a = (a == null) ? 1 : a; - this.b = b || 0; - this.c = c || 0; - this.d = (d == null) ? 1 : d; - this.tx = tx || 0; - this.ty = ty || 0; - return this; - }; - - /** - * Appends the specified matrix properties to this matrix. All parameters are required. - * This is the equivalent of multiplying `(this matrix) * (specified matrix)`. - * @method append - * @param {Number} a - * @param {Number} b - * @param {Number} c - * @param {Number} d - * @param {Number} tx - * @param {Number} ty - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.append = function(a, b, c, d, tx, ty) { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - if (a != 1 || b != 0 || c != 0 || d != 1) { - this.a = a1*a+c1*b; - this.b = b1*a+d1*b; - this.c = a1*c+c1*d; - this.d = b1*c+d1*d; - } - this.tx = a1*tx+c1*ty+this.tx; - this.ty = b1*tx+d1*ty+this.ty; - return this; - }; - - /** - * Prepends the specified matrix properties to this matrix. - * This is the equivalent of multiplying `(specified matrix) * (this matrix)`. - * All parameters are required. - * @method prepend - * @param {Number} a - * @param {Number} b - * @param {Number} c - * @param {Number} d - * @param {Number} tx - * @param {Number} ty - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.prepend = function(a, b, c, d, tx, ty) { - var a1 = this.a; - var c1 = this.c; - var tx1 = this.tx; - - this.a = a*a1+c*this.b; - this.b = b*a1+d*this.b; - this.c = a*c1+c*this.d; - this.d = b*c1+d*this.d; - this.tx = a*tx1+c*this.ty+tx; - this.ty = b*tx1+d*this.ty+ty; - return this; - }; - - /** - * Appends the specified matrix to this matrix. - * This is the equivalent of multiplying `(this matrix) * (specified matrix)`. - * @method appendMatrix - * @param {Matrix2D} matrix - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.appendMatrix = function(matrix) { - return this.append(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); - }; - - /** - * Prepends the specified matrix to this matrix. - * This is the equivalent of multiplying `(specified matrix) * (this matrix)`. - * For example, you could calculate the combined transformation for a child object using: - * - * var o = myDisplayObject; - * var mtx = o.getMatrix(); - * while (o = o.parent) { - * // prepend each parent's transformation in turn: - * o.prependMatrix(o.getMatrix()); - * } - * @method prependMatrix - * @param {Matrix2D} matrix - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.prependMatrix = function(matrix) { - return this.prepend(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); - }; - - /** - * Generates matrix properties from the specified display object transform properties, and appends them to this matrix. - * For example, you can use this to generate a matrix representing the transformations of a display object: - * - * var mtx = new Matrix2D(); - * mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation); - * @method appendTransform - * @param {Number} x - * @param {Number} y - * @param {Number} scaleX - * @param {Number} scaleY - * @param {Number} rotation - * @param {Number} skewX - * @param {Number} skewY - * @param {Number} regX Optional. - * @param {Number} regY Optional. - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.appendTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { - if (rotation%360) { - var r = rotation*Matrix2D.DEG_TO_RAD; - var cos = Math.cos(r); - var sin = Math.sin(r); - } else { - cos = 1; - sin = 0; - } - - if (skewX || skewY) { - // TODO: can this be combined into a single append operation? - skewX *= Matrix2D.DEG_TO_RAD; - skewY *= Matrix2D.DEG_TO_RAD; - this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); - this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); - } else { - this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); - } - - if (regX || regY) { - // append the registration offset: - this.tx -= regX*this.a+regY*this.c; - this.ty -= regX*this.b+regY*this.d; - } - return this; - }; - - /** - * Generates matrix properties from the specified display object transform properties, and prepends them to this matrix. - * For example, you could calculate the combined transformation for a child object using: - * - * var o = myDisplayObject; - * var mtx = new createjs.Matrix2D(); - * do { - * // prepend each parent's transformation in turn: - * mtx.prependTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.regX, o.regY); - * } while (o = o.parent); - * - * Note that the above example would not account for {{#crossLink "DisplayObject/transformMatrix:property"}}{{/crossLink}} - * values. See {{#crossLink "Matrix2D/prependMatrix"}}{{/crossLink}} for an example that does. - * @method prependTransform - * @param {Number} x - * @param {Number} y - * @param {Number} scaleX - * @param {Number} scaleY - * @param {Number} rotation - * @param {Number} skewX - * @param {Number} skewY - * @param {Number} regX Optional. - * @param {Number} regY Optional. - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.prependTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { - if (rotation%360) { - var r = rotation*Matrix2D.DEG_TO_RAD; - var cos = Math.cos(r); - var sin = Math.sin(r); - } else { - cos = 1; - sin = 0; - } - - if (regX || regY) { - // prepend the registration offset: - this.tx -= regX; this.ty -= regY; - } - if (skewX || skewY) { - // TODO: can this be combined into a single prepend operation? - skewX *= Matrix2D.DEG_TO_RAD; - skewY *= Matrix2D.DEG_TO_RAD; - this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); - this.prepend(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); - } else { - this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); - } - return this; - }; - - /** - * Applies a clockwise rotation transformation to the matrix. - * @method rotate - * @param {Number} angle The angle to rotate by, in degrees. To use a value in radians, multiply it by `180/Math.PI`. - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.rotate = function(angle) { - angle = angle*Matrix2D.DEG_TO_RAD; - var cos = Math.cos(angle); - var sin = Math.sin(angle); - - var a1 = this.a; - var b1 = this.b; - - this.a = a1*cos+this.c*sin; - this.b = b1*cos+this.d*sin; - this.c = -a1*sin+this.c*cos; - this.d = -b1*sin+this.d*cos; - return this; - }; - - /** - * Applies a skew transformation to the matrix. - * @method skew - * @param {Number} skewX The amount to skew horizontally in degrees. To use a value in radians, multiply it by `180/Math.PI`. - * @param {Number} skewY The amount to skew vertically in degrees. - * @return {Matrix2D} This matrix. Useful for chaining method calls. - */ - p.skew = function(skewX, skewY) { - skewX = skewX*Matrix2D.DEG_TO_RAD; - skewY = skewY*Matrix2D.DEG_TO_RAD; - this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), 0, 0); - return this; - }; - - /** - * Applies a scale transformation to the matrix. - * @method scale - * @param {Number} x The amount to scale horizontally. E.G. a value of 2 will double the size in the X direction, and 0.5 will halve it. - * @param {Number} y The amount to scale vertically. - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.scale = function(x, y) { - this.a *= x; - this.b *= x; - this.c *= y; - this.d *= y; - //this.tx *= x; - //this.ty *= y; - return this; - }; - - /** - * Translates the matrix on the x and y axes. - * @method translate - * @param {Number} x - * @param {Number} y - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.translate = function(x, y) { - this.tx += this.a*x + this.c*y; - this.ty += this.b*x + this.d*y; - return this; - }; - - /** - * Sets the properties of the matrix to those of an identity matrix (one that applies a null transformation). - * @method identity - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.identity = function() { - this.a = this.d = 1; - this.b = this.c = this.tx = this.ty = 0; - return this; - }; - - /** - * Inverts the matrix, causing it to perform the opposite transformation. - * @method invert - * @return {Matrix2D} This matrix. Useful for chaining method calls. - **/ - p.invert = function() { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - var tx1 = this.tx; - var n = a1*d1-b1*c1; - - this.a = d1/n; - this.b = -b1/n; - this.c = -c1/n; - this.d = a1/n; - this.tx = (c1*this.ty-d1*tx1)/n; - this.ty = -(a1*this.ty-b1*tx1)/n; - return this; - }; - - /** - * Returns true if the matrix is an identity matrix. - * @method isIdentity - * @return {Boolean} - **/ - p.isIdentity = function() { - return this.tx === 0 && this.ty === 0 && this.a === 1 && this.b === 0 && this.c === 0 && this.d === 1; - }; - - /** - * Returns true if this matrix is equal to the specified matrix (all property values are equal). - * @method equals - * @param {Matrix2D} matrix The matrix to compare. - * @return {Boolean} - **/ - p.equals = function(matrix) { - return this.tx === matrix.tx && this.ty === matrix.ty && this.a === matrix.a && this.b === matrix.b && this.c === matrix.c && this.d === matrix.d; - }; - - /** - * Transforms a point according to this matrix. - * @method transformPoint - * @param {Number} x The x component of the point to transform. - * @param {Number} y The y component of the point to transform. - * @param {Point | Object} [pt] An object to copy the result into. If omitted a generic object with x/y properties will be returned. - * @return {Point} This matrix. Useful for chaining method calls. - **/ - p.transformPoint = function(x, y, pt) { - pt = pt||{}; - pt.x = x*this.a+y*this.c+this.tx; - pt.y = x*this.b+y*this.d+this.ty; - return pt; - }; - - /** - * Decomposes the matrix into transform properties (x, y, scaleX, scaleY, and rotation). Note that these values - * may not match the transform properties you used to generate the matrix, though they will produce the same visual - * results. - * @method decompose - * @param {Object} target The object to apply the transform properties to. If null, then a new object will be returned. - * @return {Object} The target, or a new generic object with the transform properties applied. - */ - p.decompose = function(target) { - // TODO: it would be nice to be able to solve for whether the matrix can be decomposed into only scale/rotation even when scale is negative - if (target == null) { target = {}; } - target.x = this.tx; - target.y = this.ty; - target.scaleX = Math.sqrt(this.a * this.a + this.b * this.b); - target.scaleY = Math.sqrt(this.c * this.c + this.d * this.d); - - var skewX = Math.atan2(-this.c, this.d); - var skewY = Math.atan2(this.b, this.a); - - var delta = Math.abs(1-skewX/skewY); - if (delta < 0.00001) { // effectively identical, can use rotation: - target.rotation = skewY/Matrix2D.DEG_TO_RAD; - if (this.a < 0 && this.d >= 0) { - target.rotation += (target.rotation <= 0) ? 180 : -180; - } - target.skewX = target.skewY = 0; - } else { - target.skewX = skewX/Matrix2D.DEG_TO_RAD; - target.skewY = skewY/Matrix2D.DEG_TO_RAD; - } - return target; - }; - - /** - * Copies all properties from the specified matrix to this matrix. - * @method copy - * @param {Matrix2D} matrix The matrix to copy properties from. - * @return {Matrix2D} This matrix. Useful for chaining method calls. - */ - p.copy = function(matrix) { - return this.setValues(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); - }; - - /** - * Returns a clone of the Matrix2D instance. - * @method clone - * @return {Matrix2D} a clone of the Matrix2D instance. - **/ - p.clone = function() { - return new Matrix2D(this.a, this.b, this.c, this.d, this.tx, this.ty); - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Matrix2D (a="+this.a+" b="+this.b+" c="+this.c+" d="+this.d+" tx="+this.tx+" ty="+this.ty+")]"; - }; - - // this has to be populated after the class is defined: - Matrix2D.identity = new Matrix2D(); - - - createjs.Matrix2D = Matrix2D; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Represents an affine transformation matrix, and provides tools for constructing and concatenating matrices. + * + * This matrix can be visualized as: + * + * [ a c tx + * b d ty + * 0 0 1 ] + * + * Note the locations of b and c. + * + * @class Matrix2D + * @param {Number} [a=1] Specifies the a property for the new matrix. + * @param {Number} [b=0] Specifies the b property for the new matrix. + * @param {Number} [c=0] Specifies the c property for the new matrix. + * @param {Number} [d=1] Specifies the d property for the new matrix. + * @param {Number} [tx=0] Specifies the tx property for the new matrix. + * @param {Number} [ty=0] Specifies the ty property for the new matrix. + * @constructor + **/ + function Matrix2D(a, b, c, d, tx, ty) { + this.setValues(a,b,c,d,tx,ty); + + // public properties: + // assigned in the setValues method. + /** + * Position (0, 0) in a 3x3 affine transformation matrix. + * @property a + * @type Number + **/ + + /** + * Position (0, 1) in a 3x3 affine transformation matrix. + * @property b + * @type Number + **/ + + /** + * Position (1, 0) in a 3x3 affine transformation matrix. + * @property c + * @type Number + **/ + + /** + * Position (1, 1) in a 3x3 affine transformation matrix. + * @property d + * @type Number + **/ + + /** + * Position (2, 0) in a 3x3 affine transformation matrix. + * @property tx + * @type Number + **/ + + /** + * Position (2, 1) in a 3x3 affine transformation matrix. + * @property ty + * @type Number + **/ + } + var p = Matrix2D.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// constants: + /** + * Multiplier for converting degrees to radians. Used internally by Matrix2D. + * @property DEG_TO_RAD + * @static + * @final + * @type Number + * @readonly + **/ + Matrix2D.DEG_TO_RAD = Math.PI/180; + + +// static public properties: + /** + * An identity matrix, representing a null transformation. + * @property identity + * @static + * @type Matrix2D + * @readonly + **/ + Matrix2D.identity = null; // set at bottom of class definition. + + +// public methods: + /** + * Sets the specified values on this instance. + * @method setValues + * @param {Number} [a=1] Specifies the a property for the new matrix. + * @param {Number} [b=0] Specifies the b property for the new matrix. + * @param {Number} [c=0] Specifies the c property for the new matrix. + * @param {Number} [d=1] Specifies the d property for the new matrix. + * @param {Number} [tx=0] Specifies the tx property for the new matrix. + * @param {Number} [ty=0] Specifies the ty property for the new matrix. + * @return {Matrix2D} This instance. Useful for chaining method calls. + */ + p.setValues = function(a, b, c, d, tx, ty) { + // don't forget to update docs in the constructor if these change: + this.a = (a == null) ? 1 : a; + this.b = b || 0; + this.c = c || 0; + this.d = (d == null) ? 1 : d; + this.tx = tx || 0; + this.ty = ty || 0; + return this; + }; + + /** + * Appends the specified matrix properties to this matrix. All parameters are required. + * This is the equivalent of multiplying `(this matrix) * (specified matrix)`. + * @method append + * @param {Number} a + * @param {Number} b + * @param {Number} c + * @param {Number} d + * @param {Number} tx + * @param {Number} ty + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.append = function(a, b, c, d, tx, ty) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + if (a != 1 || b != 0 || c != 0 || d != 1) { + this.a = a1*a+c1*b; + this.b = b1*a+d1*b; + this.c = a1*c+c1*d; + this.d = b1*c+d1*d; + } + this.tx = a1*tx+c1*ty+this.tx; + this.ty = b1*tx+d1*ty+this.ty; + return this; + }; + + /** + * Prepends the specified matrix properties to this matrix. + * This is the equivalent of multiplying `(specified matrix) * (this matrix)`. + * All parameters are required. + * @method prepend + * @param {Number} a + * @param {Number} b + * @param {Number} c + * @param {Number} d + * @param {Number} tx + * @param {Number} ty + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.prepend = function(a, b, c, d, tx, ty) { + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a*a1+c*this.b; + this.b = b*a1+d*this.b; + this.c = a*c1+c*this.d; + this.d = b*c1+d*this.d; + this.tx = a*tx1+c*this.ty+tx; + this.ty = b*tx1+d*this.ty+ty; + return this; + }; + + /** + * Appends the specified matrix to this matrix. + * This is the equivalent of multiplying `(this matrix) * (specified matrix)`. + * @method appendMatrix + * @param {Matrix2D} matrix + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.appendMatrix = function(matrix) { + return this.append(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); + }; + + /** + * Prepends the specified matrix to this matrix. + * This is the equivalent of multiplying `(specified matrix) * (this matrix)`. + * For example, you could calculate the combined transformation for a child object using: + * + * var o = myDisplayObject; + * var mtx = o.getMatrix(); + * while (o = o.parent) { + * // prepend each parent's transformation in turn: + * o.prependMatrix(o.getMatrix()); + * } + * @method prependMatrix + * @param {Matrix2D} matrix + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.prependMatrix = function(matrix) { + return this.prepend(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); + }; + + /** + * Generates matrix properties from the specified display object transform properties, and appends them to this matrix. + * For example, you can use this to generate a matrix representing the transformations of a display object: + * + * var mtx = new createjs.Matrix2D(); + * mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation); + * @method appendTransform + * @param {Number} x + * @param {Number} y + * @param {Number} scaleX + * @param {Number} scaleY + * @param {Number} rotation + * @param {Number} skewX + * @param {Number} skewY + * @param {Number} regX Optional. + * @param {Number} regY Optional. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.appendTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { + if (rotation%360) { + var r = rotation*Matrix2D.DEG_TO_RAD; + var cos = Math.cos(r); + var sin = Math.sin(r); + } else { + cos = 1; + sin = 0; + } + + if (skewX || skewY) { + // TODO: can this be combined into a single append operation? + skewX *= Matrix2D.DEG_TO_RAD; + skewY *= Matrix2D.DEG_TO_RAD; + this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); + this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); + } else { + this.append(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); + } + + if (regX || regY) { + // append the registration offset: + this.tx -= regX*this.a+regY*this.c; + this.ty -= regX*this.b+regY*this.d; + } + return this; + }; + + /** + * Generates matrix properties from the specified display object transform properties, and prepends them to this matrix. + * For example, you could calculate the combined transformation for a child object using: + * + * var o = myDisplayObject; + * var mtx = new createjs.Matrix2D(); + * do { + * // prepend each parent's transformation in turn: + * mtx.prependTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.regX, o.regY); + * } while (o = o.parent); + * + * Note that the above example would not account for {{#crossLink "DisplayObject/transformMatrix:property"}}{{/crossLink}} + * values. See {{#crossLink "Matrix2D/prependMatrix"}}{{/crossLink}} for an example that does. + * @method prependTransform + * @param {Number} x + * @param {Number} y + * @param {Number} scaleX + * @param {Number} scaleY + * @param {Number} rotation + * @param {Number} skewX + * @param {Number} skewY + * @param {Number} regX Optional. + * @param {Number} regY Optional. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.prependTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { + if (rotation%360) { + var r = rotation*Matrix2D.DEG_TO_RAD; + var cos = Math.cos(r); + var sin = Math.sin(r); + } else { + cos = 1; + sin = 0; + } + + if (regX || regY) { + // prepend the registration offset: + this.tx -= regX; this.ty -= regY; + } + if (skewX || skewY) { + // TODO: can this be combined into a single prepend operation? + skewX *= Matrix2D.DEG_TO_RAD; + skewY *= Matrix2D.DEG_TO_RAD; + this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, 0, 0); + this.prepend(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y); + } else { + this.prepend(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, x, y); + } + return this; + }; + + /** + * Applies a clockwise rotation transformation to the matrix. + * @method rotate + * @param {Number} angle The angle to rotate by, in degrees. To use a value in radians, multiply it by `180/Math.PI`. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.rotate = function(angle) { + angle = angle*Matrix2D.DEG_TO_RAD; + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var b1 = this.b; + + this.a = a1*cos+this.c*sin; + this.b = b1*cos+this.d*sin; + this.c = -a1*sin+this.c*cos; + this.d = -b1*sin+this.d*cos; + return this; + }; + + /** + * Applies a skew transformation to the matrix. + * @method skew + * @param {Number} skewX The amount to skew horizontally in degrees. To use a value in radians, multiply it by `180/Math.PI`. + * @param {Number} skewY The amount to skew vertically in degrees. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + */ + p.skew = function(skewX, skewY) { + skewX = skewX*Matrix2D.DEG_TO_RAD; + skewY = skewY*Matrix2D.DEG_TO_RAD; + this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), 0, 0); + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * @method scale + * @param {Number} x The amount to scale horizontally. E.G. a value of 2 will double the size in the X direction, and 0.5 will halve it. + * @param {Number} y The amount to scale vertically. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.scale = function(x, y) { + this.a *= x; + this.b *= x; + this.c *= y; + this.d *= y; + //this.tx *= x; + //this.ty *= y; + return this; + }; + + /** + * Translates the matrix on the x and y axes. + * @method translate + * @param {Number} x + * @param {Number} y + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.translate = function(x, y) { + this.tx += this.a*x + this.c*y; + this.ty += this.b*x + this.d*y; + return this; + }; + + /** + * Sets the properties of the matrix to those of an identity matrix (one that applies a null transformation). + * @method identity + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.identity = function() { + this.a = this.d = 1; + this.b = this.c = this.tx = this.ty = 0; + return this; + }; + + /** + * Inverts the matrix, causing it to perform the opposite transformation. + * @method invert + * @return {Matrix2D} This matrix. Useful for chaining method calls. + **/ + p.invert = function() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1*d1-b1*c1; + + this.a = d1/n; + this.b = -b1/n; + this.c = -c1/n; + this.d = a1/n; + this.tx = (c1*this.ty-d1*tx1)/n; + this.ty = -(a1*this.ty-b1*tx1)/n; + return this; + }; + + /** + * Returns true if the matrix is an identity matrix. + * @method isIdentity + * @return {Boolean} + **/ + p.isIdentity = function() { + return this.tx === 0 && this.ty === 0 && this.a === 1 && this.b === 0 && this.c === 0 && this.d === 1; + }; + + /** + * Returns true if this matrix is equal to the specified matrix (all property values are equal). + * @method equals + * @param {Matrix2D} matrix The matrix to compare. + * @return {Boolean} + **/ + p.equals = function(matrix) { + return this.tx === matrix.tx && this.ty === matrix.ty && this.a === matrix.a && this.b === matrix.b && this.c === matrix.c && this.d === matrix.d; + }; + + /** + * Transforms a point according to this matrix. + * @method transformPoint + * @param {Number} x The x component of the point to transform. + * @param {Number} y The y component of the point to transform. + * @param {Point | Object} [pt] An object to copy the result into. If omitted a generic object with x/y properties will be returned. + * @return {Point} This matrix. Useful for chaining method calls. + **/ + p.transformPoint = function(x, y, pt) { + pt = pt||{}; + pt.x = x*this.a+y*this.c+this.tx; + pt.y = x*this.b+y*this.d+this.ty; + return pt; + }; + + /** + * Decomposes the matrix into transform properties (x, y, scaleX, scaleY, and rotation). Note that these values + * may not match the transform properties you used to generate the matrix, though they will produce the same visual + * results. + * @method decompose + * @param {Object} target The object to apply the transform properties to. If null, then a new object will be returned. + * @return {Object} The target, or a new generic object with the transform properties applied. + */ + p.decompose = function(target) { + // TODO: it would be nice to be able to solve for whether the matrix can be decomposed into only scale/rotation even when scale is negative + if (target == null) { target = {}; } + target.x = this.tx; + target.y = this.ty; + target.scaleX = Math.sqrt(this.a * this.a + this.b * this.b); + target.scaleY = Math.sqrt(this.c * this.c + this.d * this.d); + + var skewX = Math.atan2(-this.c, this.d); + var skewY = Math.atan2(this.b, this.a); + + var delta = Math.abs(1-skewX/skewY); + if (delta < 0.00001) { // effectively identical, can use rotation: + target.rotation = skewY/Matrix2D.DEG_TO_RAD; + if (this.a < 0 && this.d >= 0) { + target.rotation += (target.rotation <= 0) ? 180 : -180; + } + target.skewX = target.skewY = 0; + } else { + target.skewX = skewX/Matrix2D.DEG_TO_RAD; + target.skewY = skewY/Matrix2D.DEG_TO_RAD; + } + return target; + }; + + /** + * Copies all properties from the specified matrix to this matrix. + * @method copy + * @param {Matrix2D} matrix The matrix to copy properties from. + * @return {Matrix2D} This matrix. Useful for chaining method calls. + */ + p.copy = function(matrix) { + return this.setValues(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty); + }; + + /** + * Returns a clone of the Matrix2D instance. + * @method clone + * @return {Matrix2D} a clone of the Matrix2D instance. + **/ + p.clone = function() { + return new Matrix2D(this.a, this.b, this.c, this.d, this.tx, this.ty); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Matrix2D (a="+this.a+" b="+this.b+" c="+this.c+" d="+this.d+" tx="+this.tx+" ty="+this.ty+")]"; + }; + + // this has to be populated after the class is defined: + Matrix2D.identity = new Matrix2D(); + + + createjs.Matrix2D = Matrix2D; }()); //############################################################################## // DisplayProps.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - /** - * Used for calculating and encapsulating display related properties. - * @class DisplayProps - * @param {Number} [visible=true] Visible value. - * @param {Number} [alpha=0] Alpha value. - * @param {Number} [shadow=null] A Shadow instance or null. - * @param {Number} [compositeOperation=null] A compositeOperation value or null. - * @param {Number} [matrix] A transformation matrix. Defaults to a new identity matrix. - * @constructor - **/ - function DisplayProps(visible, alpha, shadow, compositeOperation, matrix) { - this.setValues(visible, alpha, shadow, compositeOperation, matrix); - - // public properties: - // assigned in the setValues method. - /** - * Property representing the alpha that will be applied to a display object. - * @property alpha - * @type Number - **/ - - /** - * Property representing the shadow that will be applied to a display object. - * @property shadow - * @type Shadow - **/ - - /** - * Property representing the compositeOperation that will be applied to a display object. - * You can find a list of valid composite operations at: - * https://developer.mozilla.org/en/Canvas_tutorial/Compositing - * @property compositeOperation - * @type String - **/ - - /** - * Property representing the value for visible that will be applied to a display object. - * @property visible - * @type Boolean - **/ - - /** - * The transformation matrix that will be applied to a display object. - * @property matrix - * @type Matrix2D - **/ - } - var p = DisplayProps.prototype; - -// initialization: - /** - * Reinitializes the instance with the specified values. - * @method setValues - * @param {Number} [visible=true] Visible value. - * @param {Number} [alpha=1] Alpha value. - * @param {Number} [shadow=null] A Shadow instance or null. - * @param {Number} [compositeOperation=null] A compositeOperation value or null. - * @param {Number} [matrix] A transformation matrix. Defaults to an identity matrix. - * @return {DisplayProps} This instance. Useful for chaining method calls. - * @chainable - */ - p.setValues = function (visible, alpha, shadow, compositeOperation, matrix) { - this.visible = visible == null ? true : !!visible; - this.alpha = alpha == null ? 1 : alpha; - this.shadow = shadow; - this.compositeOperation = shadow; - this.matrix = matrix || (this.matrix&&this.matrix.identity()) || new createjs.Matrix2D(); - return this; - }; - -// public methods: - /** - * Appends the specified display properties. This is generally used to apply a child's properties its parent's. - * @method append - * @param {Boolean} visible desired visible value - * @param {Number} alpha desired alpha value - * @param {Shadow} shadow desired shadow value - * @param {String} compositeOperation desired composite operation value - * @param {Matrix2D} [matrix] a Matrix2D instance - * @return {DisplayProps} This instance. Useful for chaining method calls. - * @chainable - */ - p.append = function(visible, alpha, shadow, compositeOperation, matrix) { - this.alpha *= alpha; - this.shadow = shadow || this.shadow; - this.compositeOperation = compositeOperation || this.compositeOperation; - this.visible = this.visible && visible; - matrix&&this.matrix.appendMatrix(matrix); - return this; - }; - - /** - * Prepends the specified display properties. This is generally used to apply a parent's properties to a child's. - * For example, to get the combined display properties that would be applied to a child, you could use: - * - * var o = myDisplayObject; - * var props = new createjs.DisplayProps(); - * do { - * // prepend each parent's props in turn: - * props.prepend(o.visible, o.alpha, o.shadow, o.compositeOperation, o.getMatrix()); - * } while (o = o.parent); - * - * @method prepend - * @param {Boolean} visible desired visible value - * @param {Number} alpha desired alpha value - * @param {Shadow} shadow desired shadow value - * @param {String} compositeOperation desired composite operation value - * @param {Matrix2D} [matrix] a Matrix2D instance - * @return {DisplayProps} This instance. Useful for chaining method calls. - * @chainable - */ - p.prepend = function(visible, alpha, shadow, compositeOperation, matrix) { - this.alpha *= alpha; - this.shadow = this.shadow || shadow; - this.compositeOperation = this.compositeOperation || compositeOperation; - this.visible = this.visible && visible; - matrix&&this.matrix.prependMatrix(matrix); - return this; - }; - - /** - * Resets this instance and its matrix to default values. - * @method identity - * @return {DisplayProps} This instance. Useful for chaining method calls. - * @chainable - */ - p.identity = function() { - this.visible = true; - this.alpha = 1; - this.shadow = this.compositeOperation = null; - this.matrix.identity(); - return this; - }; - - /** - * Returns a clone of the DisplayProps instance. Clones the associated matrix. - * @method clone - * @return {DisplayProps} a clone of the DisplayProps instance. - **/ - p.clone = function() { - return new DisplayProps(this.alpha, this.shadow, this.compositeOperation, this.visible, this.matrix.clone()); - }; - -// private methods: - - createjs.DisplayProps = DisplayProps; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + /** + * Used for calculating and encapsulating display related properties. + * @class DisplayProps + * @param {Number} [visible=true] Visible value. + * @param {Number} [alpha=1] Alpha value. + * @param {Number} [shadow=null] A Shadow instance or null. + * @param {Number} [compositeOperation=null] A compositeOperation value or null. + * @param {Number} [matrix] A transformation matrix. Defaults to a new identity matrix. + * @constructor + **/ + function DisplayProps(visible, alpha, shadow, compositeOperation, matrix) { + this.setValues(visible, alpha, shadow, compositeOperation, matrix); + + // public properties: + // assigned in the setValues method. + /** + * Property representing the alpha that will be applied to a display object. + * @property alpha + * @type Number + **/ + + /** + * Property representing the shadow that will be applied to a display object. + * @property shadow + * @type Shadow + **/ + + /** + * Property representing the compositeOperation that will be applied to a display object. + * You can find a list of valid composite operations at: + * https://developer.mozilla.org/en/Canvas_tutorial/Compositing + * @property compositeOperation + * @type String + **/ + + /** + * Property representing the value for visible that will be applied to a display object. + * @property visible + * @type Boolean + **/ + + /** + * The transformation matrix that will be applied to a display object. + * @property matrix + * @type Matrix2D + **/ + } + var p = DisplayProps.prototype; + +// initialization: + /** + * Reinitializes the instance with the specified values. + * @method setValues + * @param {Number} [visible=true] Visible value. + * @param {Number} [alpha=1] Alpha value. + * @param {Number} [shadow=null] A Shadow instance or null. + * @param {Number} [compositeOperation=null] A compositeOperation value or null. + * @param {Number} [matrix] A transformation matrix. Defaults to an identity matrix. + * @return {DisplayProps} This instance. Useful for chaining method calls. + * @chainable + */ + p.setValues = function (visible, alpha, shadow, compositeOperation, matrix) { + this.visible = visible == null ? true : !!visible; + this.alpha = alpha == null ? 1 : alpha; + this.shadow = shadow; + this.compositeOperation = compositeOperation; + this.matrix = matrix || (this.matrix&&this.matrix.identity()) || new createjs.Matrix2D(); + return this; + }; + +// public methods: + /** + * Appends the specified display properties. This is generally used to apply a child's properties its parent's. + * @method append + * @param {Boolean} visible desired visible value + * @param {Number} alpha desired alpha value + * @param {Shadow} shadow desired shadow value + * @param {String} compositeOperation desired composite operation value + * @param {Matrix2D} [matrix] a Matrix2D instance + * @return {DisplayProps} This instance. Useful for chaining method calls. + * @chainable + */ + p.append = function(visible, alpha, shadow, compositeOperation, matrix) { + this.alpha *= alpha; + this.shadow = shadow || this.shadow; + this.compositeOperation = compositeOperation || this.compositeOperation; + this.visible = this.visible && visible; + matrix&&this.matrix.appendMatrix(matrix); + return this; + }; + + /** + * Prepends the specified display properties. This is generally used to apply a parent's properties to a child's. + * For example, to get the combined display properties that would be applied to a child, you could use: + * + * var o = myDisplayObject; + * var props = new createjs.DisplayProps(); + * do { + * // prepend each parent's props in turn: + * props.prepend(o.visible, o.alpha, o.shadow, o.compositeOperation, o.getMatrix()); + * } while (o = o.parent); + * + * @method prepend + * @param {Boolean} visible desired visible value + * @param {Number} alpha desired alpha value + * @param {Shadow} shadow desired shadow value + * @param {String} compositeOperation desired composite operation value + * @param {Matrix2D} [matrix] a Matrix2D instance + * @return {DisplayProps} This instance. Useful for chaining method calls. + * @chainable + */ + p.prepend = function(visible, alpha, shadow, compositeOperation, matrix) { + this.alpha *= alpha; + this.shadow = this.shadow || shadow; + this.compositeOperation = this.compositeOperation || compositeOperation; + this.visible = this.visible && visible; + matrix&&this.matrix.prependMatrix(matrix); + return this; + }; + + /** + * Resets this instance and its matrix to default values. + * @method identity + * @return {DisplayProps} This instance. Useful for chaining method calls. + * @chainable + */ + p.identity = function() { + this.visible = true; + this.alpha = 1; + this.shadow = this.compositeOperation = null; + this.matrix.identity(); + return this; + }; + + /** + * Returns a clone of the DisplayProps instance. Clones the associated matrix. + * @method clone + * @return {DisplayProps} a clone of the DisplayProps instance. + **/ + p.clone = function() { + return new DisplayProps(this.alpha, this.shadow, this.compositeOperation, this.visible, this.matrix.clone()); + }; + +// private methods: + + createjs.DisplayProps = DisplayProps; })(); //############################################################################## // Point.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Represents a point on a 2 dimensional x / y coordinate system. - * - *

Example

- * - * var point = new createjs.Point(0, 100); - * - * @class Point - * @param {Number} [x=0] X position. - * @param {Number} [y=0] Y position. - * @constructor - **/ - function Point(x, y) { - this.setValues(x, y); - - - // public properties: - // assigned in the setValues method. - /** - * X position. - * @property x - * @type Number - **/ - - /** - * Y position. - * @property y - * @type Number - **/ - } - var p = Point.prototype; - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// public methods: - /** - * Sets the specified values on this instance. - * @method setValues - * @param {Number} [x=0] X position. - * @param {Number} [y=0] Y position. - * @return {Point} This instance. Useful for chaining method calls. - * @chainable - */ - p.setValues = function(x, y) { - this.x = x||0; - this.y = y||0; - return this; - }; - - /** - * Copies all properties from the specified point to this point. - * @method copy - * @param {Point} point The point to copy properties from. - * @return {Point} This point. Useful for chaining method calls. - * @chainable - */ - p.copy = function(point) { - this.x = point.x; - this.y = point.y; - return this; - }; - - /** - * Returns a clone of the Point instance. - * @method clone - * @return {Point} a clone of the Point instance. - **/ - p.clone = function() { - return new Point(this.x, this.y); - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Point (x="+this.x+" y="+this.y+")]"; - }; - - - createjs.Point = Point; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Represents a point on a 2 dimensional x / y coordinate system. + * + *

Example

+ * + * var point = new createjs.Point(0, 100); + * + * @class Point + * @param {Number} [x=0] X position. + * @param {Number} [y=0] Y position. + * @constructor + **/ + function Point(x, y) { + this.setValues(x, y); + + + // public properties: + // assigned in the setValues method. + /** + * X position. + * @property x + * @type Number + **/ + + /** + * Y position. + * @property y + * @type Number + **/ + } + var p = Point.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// public methods: + /** + * Sets the specified values on this instance. + * @method setValues + * @param {Number} [x=0] X position. + * @param {Number} [y=0] Y position. + * @return {Point} This instance. Useful for chaining method calls. + * @chainable + */ + p.setValues = function(x, y) { + this.x = x||0; + this.y = y||0; + return this; + }; + + /** + * Copies all properties from the specified point to this point. + * @method copy + * @param {Point} point The point to copy properties from. + * @return {Point} This point. Useful for chaining method calls. + * @chainable + */ + p.copy = function(point) { + this.x = point.x; + this.y = point.y; + return this; + }; + + /** + * Returns a clone of the Point instance. + * @method clone + * @return {Point} a clone of the Point instance. + **/ + p.clone = function() { + return new Point(this.x, this.y); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Point (x="+this.x+" y="+this.y+")]"; + }; + + + createjs.Point = Point; }()); //############################################################################## // Rectangle.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Represents a rectangle as defined by the points (x, y) and (x+width, y+height). - * - *

Example

- * - * var rect = new createjs.Rectangle(0, 0, 100, 100); - * - * @class Rectangle - * @param {Number} [x=0] X position. - * @param {Number} [y=0] Y position. - * @param {Number} [width=0] The width of the Rectangle. - * @param {Number} [height=0] The height of the Rectangle. - * @constructor - **/ - function Rectangle(x, y, width, height) { - this.setValues(x, y, width, height); - - - // public properties: - // assigned in the setValues method. - /** - * X position. - * @property x - * @type Number - **/ - - /** - * Y position. - * @property y - * @type Number - **/ - - /** - * Width. - * @property width - * @type Number - **/ - - /** - * Height. - * @property height - * @type Number - **/ - } - var p = Rectangle.prototype; - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// public methods: - /** - * Sets the specified values on this instance. - * @method setValues - * @param {Number} [x=0] X position. - * @param {Number} [y=0] Y position. - * @param {Number} [width=0] The width of the Rectangle. - * @param {Number} [height=0] The height of the Rectangle. - * @return {Rectangle} This instance. Useful for chaining method calls. - * @chainable - */ - p.setValues = function(x, y, width, height) { - // don't forget to update docs in the constructor if these change: - this.x = x||0; - this.y = y||0; - this.width = width||0; - this.height = height||0; - return this; - }; - - /** - * Extends the rectangle's bounds to include the described point or rectangle. - * @method extend - * @param {Number} x X position of the point or rectangle. - * @param {Number} y Y position of the point or rectangle. - * @param {Number} [width=0] The width of the rectangle. - * @param {Number} [height=0] The height of the rectangle. - * @return {Rectangle} This instance. Useful for chaining method calls. - * @chainable - */ - p.extend = function(x, y, width, height) { - width = width||0; - height = height||0; - if (x+width > this.x+this.width) { this.width = x+width-this.x; } - if (y+height > this.y+this.height) { this.height = y+height-this.y; } - if (x < this.x) { this.width += this.x-x; this.x = x; } - if (y < this.y) { this.height += this.y-y; this.y = y; } - return this; - }; - - /** - * Adds the specified padding to the rectangle's bounds. - * @method extend - * @param {Number} [top=0] - * @param {Number} [left=0] - * @param {Number} [right=0] - * @param {Number} [bottom=0] - * @return {Rectangle} This instance. Useful for chaining method calls. - * @chainable - */ - p.pad = function(top, left, bottom, right) { - this.x -= left; - this.y -= top; - this.width += left+right; - this.height += top+bottom; - return this; - }; - - /** - * Copies all properties from the specified rectangle to this rectangle. - * @method copy - * @param {Rectangle} rectangle The rectangle to copy properties from. - * @return {Rectangle} This rectangle. Useful for chaining method calls. - * @chainable - */ - p.copy = function(rectangle) { - return this.setValues(rectangle.x, rectangle.y, rectangle.width, rectangle.height); - }; - - /** - * Returns true if this rectangle fully encloses the described point or rectangle. - * @method contains - * @param {Number} x X position of the point or rectangle. - * @param {Number} y Y position of the point or rectangle. - * @param {Number} [width=0] The width of the rectangle. - * @param {Number} [height=0] The height of the rectangle. - * @return {Boolean} True if the described point or rectangle is contained within this rectangle. - */ - p.contains = function(x, y, width, height) { - width = width||0; - height = height||0; - return (x >= this.x && x+width <= this.x+this.width && y >= this.y && y+height <= this.y+this.height); - }; - - /** - * Returns a new rectangle which contains this rectangle and the specified rectangle. - * @method union - * @param {Rectangle} rect The rectangle to calculate a union with. - * @return {Rectangle} A new rectangle describing the union. - */ - p.union = function(rect) { - return this.clone().extend(rect.x, rect.y, rect.width, rect.height); - }; - - /** - * Returns a new rectangle which describes the intersection (overlap) of this rectangle and the specified rectangle, - * or null if they do not intersect. - * @method intersection - * @param {Rectangle} rect The rectangle to calculate an intersection with. - * @return {Rectangle} A new rectangle describing the intersection or null. - */ - p.intersection = function(rect) { - var x1 = rect.x, y1 = rect.y, x2 = x1+rect.width, y2 = y1+rect.height; - if (this.x > x1) { x1 = this.x; } - if (this.y > y1) { y1 = this.y; } - if (this.x + this.width < x2) { x2 = this.x + this.width; } - if (this.y + this.height < y2) { y2 = this.y + this.height; } - return (x2 <= x1 || y2 <= y1) ? null : new Rectangle(x1, y1, x2-x1, y2-y1); - }; - - /** - * Returns true if the specified rectangle intersects (has any overlap) with this rectangle. - * @method intersects - * @param {Rectangle} rect The rectangle to compare. - * @return {Boolean} True if the rectangles intersect. - */ - p.intersects = function(rect) { - return (rect.x <= this.x+this.width && this.x <= rect.x+rect.width && rect.y <= this.y+this.height && this.y <= rect.y + rect.height); - }; - - /** - * Returns true if the width or height are equal or less than 0. - * @method isEmpty - * @return {Boolean} True if the rectangle is empty. - */ - p.isEmpty = function() { - return this.width <= 0 || this.height <= 0; - }; - - /** - * Returns a clone of the Rectangle instance. - * @method clone - * @return {Rectangle} a clone of the Rectangle instance. - **/ - p.clone = function() { - return new Rectangle(this.x, this.y, this.width, this.height); - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")]"; - }; - - - createjs.Rectangle = Rectangle; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Represents a rectangle as defined by the points (x, y) and (x+width, y+height). + * + *

Example

+ * + * var rect = new createjs.Rectangle(0, 0, 100, 100); + * + * @class Rectangle + * @param {Number} [x=0] X position. + * @param {Number} [y=0] Y position. + * @param {Number} [width=0] The width of the Rectangle. + * @param {Number} [height=0] The height of the Rectangle. + * @constructor + **/ + function Rectangle(x, y, width, height) { + this.setValues(x, y, width, height); + + + // public properties: + // assigned in the setValues method. + /** + * X position. + * @property x + * @type Number + **/ + + /** + * Y position. + * @property y + * @type Number + **/ + + /** + * Width. + * @property width + * @type Number + **/ + + /** + * Height. + * @property height + * @type Number + **/ + } + var p = Rectangle.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// public methods: + /** + * Sets the specified values on this instance. + * @method setValues + * @param {Number} [x=0] X position. + * @param {Number} [y=0] Y position. + * @param {Number} [width=0] The width of the Rectangle. + * @param {Number} [height=0] The height of the Rectangle. + * @return {Rectangle} This instance. Useful for chaining method calls. + * @chainable + */ + p.setValues = function(x, y, width, height) { + // don't forget to update docs in the constructor if these change: + this.x = x||0; + this.y = y||0; + this.width = width||0; + this.height = height||0; + return this; + }; + + /** + * Extends the rectangle's bounds to include the described point or rectangle. + * @method extend + * @param {Number} x X position of the point or rectangle. + * @param {Number} y Y position of the point or rectangle. + * @param {Number} [width=0] The width of the rectangle. + * @param {Number} [height=0] The height of the rectangle. + * @return {Rectangle} This instance. Useful for chaining method calls. + * @chainable + */ + p.extend = function(x, y, width, height) { + width = width||0; + height = height||0; + if (x+width > this.x+this.width) { this.width = x+width-this.x; } + if (y+height > this.y+this.height) { this.height = y+height-this.y; } + if (x < this.x) { this.width += this.x-x; this.x = x; } + if (y < this.y) { this.height += this.y-y; this.y = y; } + return this; + }; + + /** + * Adds the specified padding to the rectangle's bounds. + * @method pad + * @param {Number} top + * @param {Number} left + * @param {Number} right + * @param {Number} bottom + * @return {Rectangle} This instance. Useful for chaining method calls. + * @chainable + */ + p.pad = function(top, left, bottom, right) { + this.x -= left; + this.y -= top; + this.width += left+right; + this.height += top+bottom; + return this; + }; + + /** + * Copies all properties from the specified rectangle to this rectangle. + * @method copy + * @param {Rectangle} rectangle The rectangle to copy properties from. + * @return {Rectangle} This rectangle. Useful for chaining method calls. + * @chainable + */ + p.copy = function(rectangle) { + return this.setValues(rectangle.x, rectangle.y, rectangle.width, rectangle.height); + }; + + /** + * Returns true if this rectangle fully encloses the described point or rectangle. + * @method contains + * @param {Number} x X position of the point or rectangle. + * @param {Number} y Y position of the point or rectangle. + * @param {Number} [width=0] The width of the rectangle. + * @param {Number} [height=0] The height of the rectangle. + * @return {Boolean} True if the described point or rectangle is contained within this rectangle. + */ + p.contains = function(x, y, width, height) { + width = width||0; + height = height||0; + return (x >= this.x && x+width <= this.x+this.width && y >= this.y && y+height <= this.y+this.height); + }; + + /** + * Returns a new rectangle which contains this rectangle and the specified rectangle. + * @method union + * @param {Rectangle} rect The rectangle to calculate a union with. + * @return {Rectangle} A new rectangle describing the union. + */ + p.union = function(rect) { + return this.clone().extend(rect.x, rect.y, rect.width, rect.height); + }; + + /** + * Returns a new rectangle which describes the intersection (overlap) of this rectangle and the specified rectangle, + * or null if they do not intersect. + * @method intersection + * @param {Rectangle} rect The rectangle to calculate an intersection with. + * @return {Rectangle} A new rectangle describing the intersection or null. + */ + p.intersection = function(rect) { + var x1 = rect.x, y1 = rect.y, x2 = x1+rect.width, y2 = y1+rect.height; + if (this.x > x1) { x1 = this.x; } + if (this.y > y1) { y1 = this.y; } + if (this.x + this.width < x2) { x2 = this.x + this.width; } + if (this.y + this.height < y2) { y2 = this.y + this.height; } + return (x2 <= x1 || y2 <= y1) ? null : new Rectangle(x1, y1, x2-x1, y2-y1); + }; + + /** + * Returns true if the specified rectangle intersects (has any overlap) with this rectangle. + * @method intersects + * @param {Rectangle} rect The rectangle to compare. + * @return {Boolean} True if the rectangles intersect. + */ + p.intersects = function(rect) { + return (rect.x <= this.x+this.width && this.x <= rect.x+rect.width && rect.y <= this.y+this.height && this.y <= rect.y + rect.height); + }; + + /** + * Returns true if the width or height are equal or less than 0. + * @method isEmpty + * @return {Boolean} True if the rectangle is empty. + */ + p.isEmpty = function() { + return this.width <= 0 || this.height <= 0; + }; + + /** + * Returns a clone of the Rectangle instance. + * @method clone + * @return {Rectangle} a clone of the Rectangle instance. + **/ + p.clone = function() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")]"; + }; + + + createjs.Rectangle = Rectangle; }()); //############################################################################## // ButtonHelper.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * The ButtonHelper is a helper class to create interactive buttons from {{#crossLink "MovieClip"}}{{/crossLink}} or - * {{#crossLink "Sprite"}}{{/crossLink}} instances. This class will intercept mouse events from an object, and - * automatically call {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} or {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}}, - * to the respective animation labels, add a pointer cursor, and allows the user to define a hit state frame. - * - * The ButtonHelper instance does not need to be added to the stage, but a reference should be maintained to prevent - * garbage collection. - * - * Note that over states will not work unless you call {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. - * - *

Example

- * - * var helper = new createjs.ButtonHelper(myInstance, "out", "over", "down", false, myInstance, "hit"); - * myInstance.addEventListener("click", handleClick); - * function handleClick(event) { - * // Click Happened. - * } - * - * @class ButtonHelper - * @param {Sprite|MovieClip} target The instance to manage. - * @param {String} [outLabel="out"] The label or animation to go to when the user rolls out of the button. - * @param {String} [overLabel="over"] The label or animation to go to when the user rolls over the button. - * @param {String} [downLabel="down"] The label or animation to go to when the user presses the button. - * @param {Boolean} [play=false] If the helper should call "gotoAndPlay" or "gotoAndStop" on the button when changing - * states. - * @param {DisplayObject} [hitArea] An optional item to use as the hit state for the button. If this is not defined, - * then the button's visible states will be used instead. Note that the same instance as the "target" argument can be - * used for the hitState. - * @param {String} [hitLabel] The label or animation on the hitArea instance that defines the hitArea bounds. If this is - * null, then the default state of the hitArea will be used. * - * @constructor - */ - function ButtonHelper(target, outLabel, overLabel, downLabel, play, hitArea, hitLabel) { - if (!target.addEventListener) { return; } - - - // public properties: - /** - * The target for this button helper. - * @property target - * @type MovieClip | Sprite - * @readonly - **/ - this.target = target; - - /** - * The label name or frame number to display when the user mouses out of the target. Defaults to "over". - * @property overLabel - * @type String | Number - **/ - this.overLabel = overLabel == null ? "over" : overLabel; - - /** - * The label name or frame number to display when the user mouses over the target. Defaults to "out". - * @property outLabel - * @type String | Number - **/ - this.outLabel = outLabel == null ? "out" : outLabel; - - /** - * The label name or frame number to display when the user presses on the target. Defaults to "down". - * @property downLabel - * @type String | Number - **/ - this.downLabel = downLabel == null ? "down" : downLabel; - - /** - * If true, then ButtonHelper will call gotoAndPlay, if false, it will use gotoAndStop. Default is false. - * @property play - * @default false - * @type Boolean - **/ - this.play = play; - - - // private properties - /** - * @property _isPressed - * @type Boolean - * @protected - **/ - this._isPressed = false; - - /** - * @property _isOver - * @type Boolean - * @protected - **/ - this._isOver = false; - - /** - * @property _enabled - * @type Boolean - * @protected - **/ - this._enabled = false; - - // setup: - target.mouseChildren = false; // prevents issues when children are removed from the display list when state changes. - this.enabled = true; - this.handleEvent({}); - if (hitArea) { - if (hitLabel) { - hitArea.actionsEnabled = false; - hitArea.gotoAndStop&&hitArea.gotoAndStop(hitLabel); - } - target.hitArea = hitArea; - } - } - var p = ButtonHelper.prototype; - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// getter / setters: - /** - * Use the {{#crossLink "ButtonHelper/enabled:property"}}{{/crossLink}} property instead. - * @method setEnabled - * @param {Boolean} value - * @deprecated - **/ - p.setEnabled = function(value) { // TODO: deprecated. - if (value == this._enabled) { return; } - var o = this.target; - this._enabled = value; - if (value) { - o.cursor = "pointer"; - o.addEventListener("rollover", this); - o.addEventListener("rollout", this); - o.addEventListener("mousedown", this); - o.addEventListener("pressup", this); - if (o._reset) { o.__reset = o._reset; o._reset = this._reset;} - } else { - o.cursor = null; - o.removeEventListener("rollover", this); - o.removeEventListener("rollout", this); - o.removeEventListener("mousedown", this); - o.removeEventListener("pressup", this); - if (o.__reset) { o._reset = o.__reset; delete(o.__reset); } - } - }; - /** - * Use the {{#crossLink "ButtonHelper/enabled:property"}}{{/crossLink}} property instead. - * @method getEnabled - * @return {Boolean} - * @deprecated - **/ - p.getEnabled = function() { - return this._enabled; - }; - - /** - * Enables or disables the button functionality on the target. - * @property enabled - * @type {Boolean} - **/ - try { - Object.defineProperties(p, { - enabled: { get: p.getEnabled, set: p.setEnabled } - }); - } catch (e) {} // TODO: use Log - - -// public methods: - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[ButtonHelper]"; - }; - - -// private methods: - /** - * @method handleEvent - * @param {Object} evt The mouse event to handle. - * @protected - **/ - p.handleEvent = function(evt) { - var label, t = this.target, type = evt.type; - if (type == "mousedown") { - this._isPressed = true; - label = this.downLabel; - } else if (type == "pressup") { - this._isPressed = false; - label = this._isOver ? this.overLabel : this.outLabel; - } else if (type == "rollover") { - this._isOver = true; - label = this._isPressed ? this.downLabel : this.overLabel; - } else { // rollout and default - this._isOver = false; - label = this._isPressed ? this.overLabel : this.outLabel; - } - if (this.play) { - t.gotoAndPlay&&t.gotoAndPlay(label); - } else { - t.gotoAndStop&&t.gotoAndStop(label); - } - }; - - /** - * Injected into target. Preserves the paused state through a reset. - * @method _reset - * @protected - **/ - p._reset = function() { - // TODO: explore better ways to handle this issue. This is hacky & disrupts object signatures. - var p = this.paused; - this.__reset(); - this.paused = p; - }; - - - createjs.ButtonHelper = ButtonHelper; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * The ButtonHelper is a helper class to create interactive buttons from {{#crossLink "MovieClip"}}{{/crossLink}} or + * {{#crossLink "Sprite"}}{{/crossLink}} instances. This class will intercept mouse events from an object, and + * automatically call {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} or {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}}, + * to the respective animation labels, add a pointer cursor, and allows the user to define a hit state frame. + * + * The ButtonHelper instance does not need to be added to the stage, but a reference should be maintained to prevent + * garbage collection. + * + * Note that over states will not work unless you call {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. + * + *

Example

+ * + * var helper = new createjs.ButtonHelper(myInstance, "out", "over", "down", false, myInstance, "hit"); + * myInstance.addEventListener("click", handleClick); + * function handleClick(event) { + * // Click Happened. + * } + * + * @class ButtonHelper + * @param {Sprite|MovieClip} target The instance to manage. + * @param {String} [outLabel="out"] The label or animation to go to when the user rolls out of the button. + * @param {String} [overLabel="over"] The label or animation to go to when the user rolls over the button. + * @param {String} [downLabel="down"] The label or animation to go to when the user presses the button. + * @param {Boolean} [play=false] If the helper should call "gotoAndPlay" or "gotoAndStop" on the button when changing + * states. + * @param {DisplayObject} [hitArea] An optional item to use as the hit state for the button. If this is not defined, + * then the button's visible states will be used instead. Note that the same instance as the "target" argument can be + * used for the hitState. + * @param {String} [hitLabel] The label or animation on the hitArea instance that defines the hitArea bounds. If this is + * null, then the default state of the hitArea will be used. * + * @constructor + */ + function ButtonHelper(target, outLabel, overLabel, downLabel, play, hitArea, hitLabel) { + if (!target.addEventListener) { return; } + + + // public properties: + /** + * The target for this button helper. + * @property target + * @type MovieClip | Sprite + * @readonly + **/ + this.target = target; + + /** + * The label name or frame number to display when the user mouses out of the target. Defaults to "over". + * @property overLabel + * @type String | Number + **/ + this.overLabel = overLabel == null ? "over" : overLabel; + + /** + * The label name or frame number to display when the user mouses over the target. Defaults to "out". + * @property outLabel + * @type String | Number + **/ + this.outLabel = outLabel == null ? "out" : outLabel; + + /** + * The label name or frame number to display when the user presses on the target. Defaults to "down". + * @property downLabel + * @type String | Number + **/ + this.downLabel = downLabel == null ? "down" : downLabel; + + /** + * If true, then ButtonHelper will call gotoAndPlay, if false, it will use gotoAndStop. Default is false. + * @property play + * @default false + * @type Boolean + **/ + this.play = play; + + + // private properties + /** + * @property _isPressed + * @type Boolean + * @protected + **/ + this._isPressed = false; + + /** + * @property _isOver + * @type Boolean + * @protected + **/ + this._isOver = false; + + /** + * @property _enabled + * @type Boolean + * @protected + **/ + this._enabled = false; + + // setup: + target.mouseChildren = false; // prevents issues when children are removed from the display list when state changes. + this.enabled = true; + this.handleEvent({}); + if (hitArea) { + if (hitLabel) { + hitArea.actionsEnabled = false; + hitArea.gotoAndStop&&hitArea.gotoAndStop(hitLabel); + } + target.hitArea = hitArea; + } + } + var p = ButtonHelper.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// getter / setters: + /** + * Use the {{#crossLink "ButtonHelper/enabled:property"}}{{/crossLink}} property instead. + * @method setEnabled + * @param {Boolean} value + * @deprecated + **/ + p.setEnabled = function(value) { // TODO: deprecated. + if (value == this._enabled) { return; } + var o = this.target; + this._enabled = value; + if (value) { + o.cursor = "pointer"; + o.addEventListener("rollover", this); + o.addEventListener("rollout", this); + o.addEventListener("mousedown", this); + o.addEventListener("pressup", this); + if (o._reset) { o.__reset = o._reset; o._reset = this._reset;} + } else { + o.cursor = null; + o.removeEventListener("rollover", this); + o.removeEventListener("rollout", this); + o.removeEventListener("mousedown", this); + o.removeEventListener("pressup", this); + if (o.__reset) { o._reset = o.__reset; delete(o.__reset); } + } + }; + /** + * Use the {{#crossLink "ButtonHelper/enabled:property"}}{{/crossLink}} property instead. + * @method getEnabled + * @return {Boolean} + * @deprecated + **/ + p.getEnabled = function() { + return this._enabled; + }; + + /** + * Enables or disables the button functionality on the target. + * @property enabled + * @type {Boolean} + **/ + try { + Object.defineProperties(p, { + enabled: { get: p.getEnabled, set: p.setEnabled } + }); + } catch (e) {} // TODO: use Log + + +// public methods: + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[ButtonHelper]"; + }; + + +// private methods: + /** + * @method handleEvent + * @param {Object} evt The mouse event to handle. + * @protected + **/ + p.handleEvent = function(evt) { + var label, t = this.target, type = evt.type; + if (type == "mousedown") { + this._isPressed = true; + label = this.downLabel; + } else if (type == "pressup") { + this._isPressed = false; + label = this._isOver ? this.overLabel : this.outLabel; + } else if (type == "rollover") { + this._isOver = true; + label = this._isPressed ? this.downLabel : this.overLabel; + } else { // rollout and default + this._isOver = false; + label = this._isPressed ? this.overLabel : this.outLabel; + } + if (this.play) { + t.gotoAndPlay&&t.gotoAndPlay(label); + } else { + t.gotoAndStop&&t.gotoAndStop(label); + } + }; + + /** + * Injected into target. Preserves the paused state through a reset. + * @method _reset + * @protected + **/ + p._reset = function() { + // TODO: explore better ways to handle this issue. This is hacky & disrupts object signatures. + var p = this.paused; + this.__reset(); + this.paused = p; + }; + + + createjs.ButtonHelper = ButtonHelper; }()); //############################################################################## // Shadow.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * This class encapsulates the properties required to define a shadow to apply to a {{#crossLink "DisplayObject"}}{{/crossLink}} - * via its shadow property. - * - *

Example

- * - * myImage.shadow = new createjs.Shadow("#000000", 5, 5, 10); - * - * @class Shadow - * @constructor - * @param {String} color The color of the shadow. This can be any valid CSS color value. - * @param {Number} offsetX The x offset of the shadow in pixels. - * @param {Number} offsetY The y offset of the shadow in pixels. - * @param {Number} blur The size of the blurring effect. - **/ - function Shadow(color, offsetX, offsetY, blur) { - - - // public properties: - /** - * The color of the shadow. This can be any valid CSS color value. - * @property color - * @type String - * @default null - */ - this.color = color||"black"; - - /** The x offset of the shadow. - * @property offsetX - * @type Number - * @default 0 - */ - this.offsetX = offsetX||0; - - /** The y offset of the shadow. - * @property offsetY - * @type Number - * @default 0 - */ - this.offsetY = offsetY||0; - - /** The blur of the shadow. - * @property blur - * @type Number - * @default 0 - */ - this.blur = blur||0; - } - var p = Shadow.prototype; - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// static public properties: - /** - * An identity shadow object (all properties are set to 0). - * @property identity - * @type Shadow - * @static - * @final - * @readonly - **/ - Shadow.identity = new Shadow("transparent", 0, 0, 0); - - -// public methods: - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Shadow]"; - }; - - /** - * Returns a clone of this Shadow instance. - * @method clone - * @return {Shadow} A clone of the current Shadow instance. - **/ - p.clone = function() { - return new Shadow(this.color, this.offsetX, this.offsetY, this.blur); - }; - - - createjs.Shadow = Shadow; -}()); - -//############################################################################## -// SpriteSheet.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Encapsulates the properties and methods associated with a sprite sheet. A sprite sheet is a series of images (usually - * animation frames) combined into a larger image (or images). For example, an animation consisting of eight 100x100 - * images could be combined into a single 400x200 sprite sheet (4 frames across by 2 high). - * - * The data passed to the SpriteSheet constructor defines:
    - *
  1. The source image or images to use.
  2. - *
  3. The positions of individual image frames.
  4. - *
  5. Sequences of frames that form named animations. Optional.
  6. - *
  7. The target playback framerate. Optional.
  8. - *
- * - *

SpriteSheet Format

- * - * SpriteSheets are an object with two required properties (`images` and `frames`), and two optional properties - * (`framerate` and `animations`). This makes them easy to define in javascript code, or in JSON. - * - *

images

- * An array of source images. Images can be either an HTMLImage - * instance, or a uri to an image. The former is recommended to control preloading. - * - * images: [image1, "path/to/image2.png"], - * - *

frames

- * Defines the individual frames. There are two supported formats for frame data:
    - *
  1. when all of the frames are the same size (in a grid), use an object with `width`, `height`, `regX`, `regY`, and `count` properties. - * `width` & `height` are required and specify the dimensions of the frames. - * `regX` & `regY` indicate the registration point or "origin" of the frames. - * `spacing` indicate the spacing between frames. - * `margin` specify the margin around the image(s). - * `count` allows you to specify the total number of frames in the spritesheet; if omitted, this will be calculated - * based on the dimensions of the source images and the frames. Frames will be assigned indexes based on their position - * in the source images (left to right, top to bottom). - * - * frames: {width:64, height:64, count:20, regX: 32, regY:64, spacing:0, margin:0} - * - *
  2. if the frames are of different sizes, use an array of frame definitions. Each definition is itself an array - * with 4 required and 3 optional entries, in the order: `x`, `y`, `width`, `height`, `imageIndex`, `regX`, `regY`. The first - * four entries are required and define the frame rectangle. The fifth specifies the index of the source image (defaults to 0). The - * last two specify the registration point of the frame. - * - * frames: [ - * // x, y, width, height, imageIndex*, regX*, regY* - * [64, 0, 96, 64], - * [0, 0, 64, 64, 1, 32, 32] - * // etc. - * ] - * - *
- * - *

animations

- * Optional. An object defining sequences of frames to play as named animations. Each property corresponds to an - * animation of the same name. Each animation must specify the frames to play, and may - * also include a relative playback `speed` (ex. 2 would playback at double speed, 0.5 at half), and - * the name of the `next` animation to sequence to after it completes. - * - * There are three formats supported for defining the frames in an animation, which can be mixed and matched as appropriate:
    - *
  1. for a single frame animation, you can simply specify the frame index - * - * animations: { - * sit: 7 - * } - * - *
  2. for an animation of consecutive frames, you can use an array with two required, and two optional entries - * in the order: `start`, `end`, `next`, and `speed`. This will play the frames from start to end inclusive. - * - * animations: { - * // start, end, next*, speed* - * run: [0, 8], - * jump: [9, 12, "run", 2] - * } - * - *
  3. for non-consecutive frames, you can use an object with a `frames` property defining an array of frame indexes to - * play in order. The object can also specify `next` and `speed` properties. - * - * animations: { - * walk: { - * frames: [1,2,3,3,2,1] - * }, - * shoot: { - * frames: [1,4,5,6], - * next: "walk", - * speed: 0.5 - * } - * } - * - *
- * Note: the `speed` property was added in EaselJS 0.7.0. Earlier versions had a `frequency` - * property instead, which was the inverse of `speed`. For example, a value of "4" would be 1/4 normal speed in earlier - * versions, but is 4x normal speed in 0.7.0+. - * - *

framerate

- * Optional. Indicates the default framerate to play this spritesheet at in frames per second. - * See {{#crossLink "SpriteSheet/framerate:property"}}{{/crossLink}} for more information. - * - * framerate: 20 - * - *

Example

- * To define a simple sprite sheet, with a single image "sprites.jpg" arranged in a regular 50x50 grid with three - * animations: "stand" showing the first frame, "run" looping frame 1-5 inclusive, and "jump" playing frame 6-8 and sequencing back to run. - * - * var data = { - * images: ["sprites.jpg"], - * frames: {width:50, height:50}, - * animations: { - * stand:0, - * run:[1,5], - * jump:[6,8,"run"] - * } - * }; - * var spriteSheet = new createjs.SpriteSheet(data); - * var animation = new createjs.Sprite(spriteSheet, "run"); - * - * - * Warning: Images loaded cross-origin will throw cross-origin security errors when interacted with - * using a mouse, using methods such as `getObjectUnderPoint`, using filters, or caching. You can get around this by - * setting `crossOrigin` flags on your images before passing them to EaselJS, eg: `img.crossOrigin="Anonymous";` - * - * @class SpriteSheet - * @constructor - * @param {Object} data An object describing the SpriteSheet data. - * @extends EventDispatcher - **/ - function SpriteSheet(data) { - this.EventDispatcher_constructor(); - - - // public properties: - /** - * Indicates whether all images are finished loading. - * @property complete - * @type Boolean - * @readonly - **/ - this.complete = true; - - /** - * Specifies the framerate to use by default for Sprite instances using the SpriteSheet. See - * Sprite.framerate for more information. - * @property framerate - * @type Number - **/ - this.framerate = 0; - - - // private properties: - /** - * @property _animations - * @protected - * @type Array - **/ - this._animations = null; - - /** - * @property _frames - * @protected - * @type Array - **/ - this._frames = null; - - /** - * @property _images - * @protected - * @type Array - **/ - this._images = null; - - /** - * @property _data - * @protected - * @type Object - **/ - this._data = null; - - /** - * @property _loadCount - * @protected - * @type Number - **/ - this._loadCount = 0; - - // only used for simple frame defs: - /** - * @property _frameHeight - * @protected - * @type Number - **/ - this._frameHeight = 0; - - /** - * @property _frameWidth - * @protected - * @type Number - **/ - this._frameWidth = 0; - - /** - * @property _numFrames - * @protected - * @type Number - **/ - this._numFrames = 0; - - /** - * @property _regX - * @protected - * @type Number - **/ - this._regX = 0; - - /** - * @property _regY - * @protected - * @type Number - **/ - this._regY = 0; - - /** - * @property _spacing - * @protected - * @type Number - **/ - this._spacing = 0; - - /** - * @property _margin - * @protected - * @type Number - **/ - this._margin = 0; - - // setup: - this._parseData(data); - } - var p = createjs.extend(SpriteSheet, createjs.EventDispatcher); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// events: - /** - * Dispatched when all images are loaded. Note that this only fires if the images - * were not fully loaded when the sprite sheet was initialized. You should check the complete property - * to prior to adding a listener. Ex. - * - * var sheet = new SpriteSheet(data); - * if (!sheet.complete) { - * // not preloaded, listen for the complete event: - * sheet.addEventListener("complete", handler); - * } - * - * @event complete - * @param {Object} target The object that dispatched the event. - * @param {String} type The event type. - * @since 0.6.0 - */ - - /** - * Dispatched when getFrame is called with a valid frame index. This is primarily intended for use by {{#crossLink "SpriteSheetBuilder"}}{{/crossLink}} - * when doing on-demand rendering. - * @event getframe - * @param {Number} index The frame index. - * @param {Object} frame The frame object that getFrame will return. - */ - - -// getter / setters: - /** - * Use the {{#crossLink "SpriteSheet/animations:property"}}{{/crossLink}} property instead. - * @method getAnimations - * @return {Array} - * @deprecated - **/ - p.getAnimations = function() { - return this._animations.slice(); - }; - - /** - * Returns an array of all available animation names available on this sprite sheet as strings. - * @property animations - * @type {Array} - * @readonly - **/ - try { - Object.defineProperties(p, { - animations: { get: p.getAnimations } - }); - } catch (e) {} - - -// public methods: - /** - * Returns the total number of frames in the specified animation, or in the whole sprite - * sheet if the animation param is omitted. Returns 0 if the spritesheet relies on calculated frame counts, and - * the images have not been fully loaded. - * @method getNumFrames - * @param {String} animation The name of the animation to get a frame count for. - * @return {Number} The number of frames in the animation, or in the entire sprite sheet if the animation param is omitted. - */ - p.getNumFrames = function(animation) { - if (animation == null) { - return this._frames ? this._frames.length : this._numFrames || 0; - } else { - var data = this._data[animation]; - if (data == null) { return 0; } - else { return data.frames.length; } - } - }; - - /** - * Returns an object defining the specified animation. The returned object contains: - * @method getAnimation - * @param {String} name The name of the animation to get. - * @return {Object} a generic object with frames, speed, name, and next properties. - **/ - p.getAnimation = function(name) { - return this._data[name]; - }; - - /** - * Returns an object specifying the image and source rect of the specified frame. The returned object has: - * @method getFrame - * @param {Number} frameIndex The index of the frame. - * @return {Object} a generic object with image and rect properties. Returns null if the frame does not exist. - **/ - p.getFrame = function(frameIndex) { - var frame; - if (this._frames && (frame=this._frames[frameIndex])) { return frame; } - return null; - }; - - /** - * Returns a {{#crossLink "Rectangle"}}{{/crossLink}} instance defining the bounds of the specified frame relative - * to the origin. For example, a 90 x 70 frame with a regX of 50 and a regY of 40 would return: - * - * [x=-50, y=-40, width=90, height=70] - * - * @method getFrameBounds - * @param {Number} frameIndex The index of the frame. - * @param {Rectangle} [rectangle] A Rectangle instance to copy the values into. By default a new instance is created. - * @return {Rectangle} A Rectangle instance. Returns null if the frame does not exist, or the image is not fully loaded. - **/ - p.getFrameBounds = function(frameIndex, rectangle) { - var frame = this.getFrame(frameIndex); - return frame ? (rectangle||new createjs.Rectangle()).setValues(-frame.regX, -frame.regY, frame.rect.width, frame.rect.height) : null; - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[SpriteSheet]"; - }; - - /** - * SpriteSheet cannot be cloned. A SpriteSheet can be shared by multiple Sprite instances without cloning it. - * @method clone - **/ - p.clone = function() { - throw("SpriteSheet cannot be cloned.") - }; - -// private methods: - /** - * @method _parseData - * @param {Object} data An object describing the SpriteSheet data. - * @protected - **/ - p._parseData = function(data) { - var i,l,o,a; - if (data == null) { return; } - - this.framerate = data.framerate||0; - - // parse images: - if (data.images && (l=data.images.length) > 0) { - a = this._images = []; - for (i=0; ishadow property. + * + *

Example

+ * + * myImage.shadow = new createjs.Shadow("#000000", 5, 5, 10); + * + * @class Shadow + * @constructor + * @param {String} color The color of the shadow. This can be any valid CSS color value. + * @param {Number} offsetX The x offset of the shadow in pixels. + * @param {Number} offsetY The y offset of the shadow in pixels. + * @param {Number} blur The size of the blurring effect. + **/ + function Shadow(color, offsetX, offsetY, blur) { + + + // public properties: + /** + * The color of the shadow. This can be any valid CSS color value. + * @property color + * @type String + * @default null + */ + this.color = color||"black"; + + /** The x offset of the shadow. + * @property offsetX + * @type Number + * @default 0 + */ + this.offsetX = offsetX||0; + + /** The y offset of the shadow. + * @property offsetY + * @type Number + * @default 0 + */ + this.offsetY = offsetY||0; + + /** The blur of the shadow. + * @property blur + * @type Number + * @default 0 + */ + this.blur = blur||0; + } + var p = Shadow.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// static public properties: + /** + * An identity shadow object (all properties are set to 0). + * @property identity + * @type Shadow + * @static + * @final + * @readonly + **/ + Shadow.identity = new Shadow("transparent", 0, 0, 0); + + +// public methods: + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Shadow]"; + }; + + /** + * Returns a clone of this Shadow instance. + * @method clone + * @return {Shadow} A clone of the current Shadow instance. + **/ + p.clone = function() { + return new Shadow(this.color, this.offsetX, this.offsetY, this.blur); + }; + + + createjs.Shadow = Shadow; +}()); - var maxFrames = this._numFrames || 100000; // if we go over this, something is wrong. - var frameCount = 0, frameWidth = this._frameWidth, frameHeight = this._frameHeight; - var spacing = this._spacing, margin = this._margin; - - imgLoop: - for (var i=0, imgs=this._images; i= maxFrames) { break imgLoop; } - frameCount++; - this._frames.push({ - image: img, - rect: new createjs.Rectangle(x, y, frameWidth, frameHeight), - regX: this._regX, - regY: this._regY - }); - x += frameWidth+spacing; - } - y += frameHeight+spacing; - } - } - this._numFrames = frameCount; - }; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Encapsulates the properties and methods associated with a sprite sheet. A sprite sheet is a series of images (usually + * animation frames) combined into a larger image (or images). For example, an animation consisting of eight 100x100 + * images could be combined into a single 400x200 sprite sheet (4 frames across by 2 high). + * + * The data passed to the SpriteSheet constructor defines: + *
    + *
  1. The source image or images to use.
  2. + *
  3. The positions of individual image frames.
  4. + *
  5. Sequences of frames that form named animations. Optional.
  6. + *
  7. The target playback framerate. Optional.
  8. + *
+ *

SpriteSheet Format

+ * SpriteSheets are an object with two required properties (`images` and `frames`), and two optional properties + * (`framerate` and `animations`). This makes them easy to define in javascript code, or in JSON. + * + *

images

+ * An array of source images. Images can be either an HTMlimage + * instance, or a uri to an image. The former is recommended to control preloading. + * + * images: [image1, "path/to/image2.png"], + * + *

frames

+ * Defines the individual frames. There are two supported formats for frame data: + * When all of the frames are the same size (in a grid), use an object with `width`, `height`, `regX`, `regY`, + * and `count` properties. + * + *
    + *
  • `width` & `height` are required and specify the dimensions of the frames
  • + *
  • `regX` & `regY` indicate the registration point or "origin" of the frames
  • + *
  • `spacing` indicate the spacing between frames
  • + *
  • `margin` specify the margin around the image(s)
  • + *
  • `count` allows you to specify the total number of frames in the spritesheet; if omitted, this will + * be calculated based on the dimensions of the source images and the frames. Frames will be assigned + * indexes based on their position in the source images (left to right, top to bottom).
  • + *
+ * + * frames: {width:64, height:64, count:20, regX: 32, regY:64, spacing:0, margin:0} + * + * If the frames are of different sizes, use an array of frame definitions. Each definition is itself an array + * with 4 required and 3 optional entries, in the order: + * + *
    + *
  • The first four, `x`, `y`, `width`, and `height` are required and define the frame rectangle.
  • + *
  • The fifth, `imageIndex`, specifies the index of the source image (defaults to 0)
  • + *
  • The last two, `regX` and `regY` specify the registration point of the frame
  • + *
+ * + * frames: [ + * // x, y, width, height, imageIndex*, regX*, regY* + * [64, 0, 96, 64], + * [0, 0, 64, 64, 1, 32, 32] + * // etc. + * ] + * + *

animations

+ * Optional. An object defining sequences of frames to play as named animations. Each property corresponds to an + * animation of the same name. Each animation must specify the frames to play, and may + * also include a relative playback `speed` (ex. 2 would playback at double speed, 0.5 at half), and + * the name of the `next` animation to sequence to after it completes. + * + * There are three formats supported for defining the frames in an animation, which can be mixed and matched as appropriate: + *
    + *
  1. for a single frame animation, you can simply specify the frame index + * + * animations: { + * sit: 7 + * } + * + *
  2. + *
  3. + * for an animation of consecutive frames, you can use an array with two required, and two optional entries + * in the order: `start`, `end`, `next`, and `speed`. This will play the frames from start to end inclusive. + * + * animations: { + * // start, end, next*, speed* + * run: [0, 8], + * jump: [9, 12, "run", 2] + * } + * + *
  4. + *
  5. + * for non-consecutive frames, you can use an object with a `frames` property defining an array of frame + * indexes to play in order. The object can also specify `next` and `speed` properties. + * + * animations: { + * walk: { + * frames: [1,2,3,3,2,1] + * }, + * shoot: { + * frames: [1,4,5,6], + * next: "walk", + * speed: 0.5 + * } + * } + * + *
  6. + *
+ * Note: the `speed` property was added in EaselJS 0.7.0. Earlier versions had a `frequency` + * property instead, which was the inverse of `speed`. For example, a value of "4" would be 1/4 normal speed in + * earlier versions, but is 4x normal speed in EaselJS 0.7.0+. + * + *

framerate

+ * Optional. Indicates the default framerate to play this spritesheet at in frames per second. See + * {{#crossLink "SpriteSheet/framerate:property"}}{{/crossLink}} for more information. + * + * framerate: 20 + * + * Note that the Sprite framerate will only work if the stage update method is provided with the {{#crossLink "Ticker/tick:event"}}{{/crossLink}} + * event generated by the {{#crossLink "Ticker"}}{{/crossLink}}. + * + * createjs.Ticker.on("tick", handleTick); + * function handleTick(event) { + * stage.update(event); + * } + * + *

Example

+ * To define a simple sprite sheet, with a single image "sprites.jpg" arranged in a regular 50x50 grid with three + * animations: "stand" showing the first frame, "run" looping frame 1-5 inclusive, and "jump" playing frame 6-8 and + * sequencing back to run. + * + * var data = { + * images: ["sprites.jpg"], + * frames: {width:50, height:50}, + * animations: { + * stand:0, + * run:[1,5], + * jump:[6,8,"run"] + * } + * }; + * var spriteSheet = new createjs.SpriteSheet(data); + * var animation = new createjs.Sprite(spriteSheet, "run"); + * + *

Generating SpriteSheet Images

+ * Spritesheets can be created manually by combining images in PhotoShop, and specifying the frame size or + * coordinates manually, however there are a number of tools that facilitate this. + *
    + *
  • Exporting SpriteSheets or HTML5 content from Flash Pro supports the EaselJS SpriteSheet format.
  • + *
  • The popular Texture Packer has + * EaselJS support. + *
  • SWF animations in Flash can be exported to SpriteSheets using
  • + *
+ * + *

Cross Origin Issues

+ * Warning: Images loaded cross-origin will throw cross-origin security errors when interacted with + * using: + *
    + *
  • a mouse
  • + *
  • methods such as {{#crossLink "Container/getObjectUnderPoint"}}{{/crossLink}}
  • + *
  • Filters (see {{#crossLink "Filter"}}{{/crossLink}})
  • + *
  • caching (see {{#crossLink "DisplayObject/cache"}}{{/crossLink}})
  • + *
+ * You can get around this by setting `crossOrigin` property on your images before passing them to EaselJS, or + * setting the `crossOrigin` property on PreloadJS' LoadQueue or LoadItems. + * + * var image = new Image(); + * img.crossOrigin="Anonymous"; + * img.src = "http://server-with-CORS-support.com/path/to/image.jpg"; + * + * If you pass string paths to SpriteSheets, they will not work cross-origin. The server that stores the image must + * support cross-origin requests, or this will not work. For more information, check out + * CORS overview on MDN. + * + * @class SpriteSheet + * @constructor + * @param {Object} data An object describing the SpriteSheet data. + * @extends EventDispatcher + **/ + function SpriteSheet(data) { + this.EventDispatcher_constructor(); + + + // public properties: + /** + * Indicates whether all images are finished loading. + * @property complete + * @type Boolean + * @readonly + **/ + this.complete = true; + + /** + * Specifies the framerate to use by default for Sprite instances using the SpriteSheet. See the Sprite class + * {{#crossLink "Sprite/framerate:property"}}{{/crossLink}} for more information. + * @property framerate + * @type Number + **/ + this.framerate = 0; + + + // private properties: + /** + * @property _animations + * @protected + * @type Array + **/ + this._animations = null; + + /** + * @property _frames + * @protected + * @type Array + **/ + this._frames = null; + + /** + * @property _images + * @protected + * @type Array + **/ + this._images = null; + + /** + * @property _data + * @protected + * @type Object + **/ + this._data = null; + + /** + * @property _loadCount + * @protected + * @type Number + **/ + this._loadCount = 0; + + // only used for simple frame defs: + /** + * @property _frameHeight + * @protected + * @type Number + **/ + this._frameHeight = 0; + + /** + * @property _frameWidth + * @protected + * @type Number + **/ + this._frameWidth = 0; + + /** + * @property _numFrames + * @protected + * @type Number + **/ + this._numFrames = 0; + + /** + * @property _regX + * @protected + * @type Number + **/ + this._regX = 0; + + /** + * @property _regY + * @protected + * @type Number + **/ + this._regY = 0; + + /** + * @property _spacing + * @protected + * @type Number + **/ + this._spacing = 0; + + /** + * @property _margin + * @protected + * @type Number + **/ + this._margin = 0; + + // setup: + this._parseData(data); + } + var p = createjs.extend(SpriteSheet, createjs.EventDispatcher); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// events: + /** + * Dispatched when all images are loaded. Note that this only fires if the images + * were not fully loaded when the sprite sheet was initialized. You should check the complete property + * to prior to adding a listener. Ex. + * + * var sheet = new createjs.SpriteSheet(data); + * if (!sheet.complete) { + * // not preloaded, listen for the complete event: + * sheet.addEventListener("complete", handler); + * } + * + * @event complete + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @since 0.6.0 + */ + + /** + * Dispatched when getFrame is called with a valid frame index. This is primarily intended for use by {{#crossLink "SpriteSheetBuilder"}}{{/crossLink}} + * when doing on-demand rendering. + * @event getframe + * @param {Number} index The frame index. + * @param {Object} frame The frame object that getFrame will return. + */ + + /** + * Dispatched when an image encounters an error. A SpriteSheet will dispatch an error event for each image that + * encounters an error, and will still dispatch a {{#crossLink "SpriteSheet/complete:event"}}{{/crossLink}} + * event once all images are finished processing, even if an error is encountered. + * @event error + * @param {String} src The source of the image that failed to load. + * @since 0.8.2 + */ + + +// getter / setters: + /** + * Use the {{#crossLink "SpriteSheet/animations:property"}}{{/crossLink}} property instead. + * @method getAnimations + * @return {Array} + * @deprecated + **/ + p.getAnimations = function() { + return this._animations.slice(); + }; + + /** + * Returns an array of all available animation names available on this sprite sheet as strings. + * @property animations + * @type {Array} + * @readonly + **/ + try { + Object.defineProperties(p, { + animations: { get: p.getAnimations } + }); + } catch (e) {} + + +// public methods: + /** + * Returns the total number of frames in the specified animation, or in the whole sprite + * sheet if the animation param is omitted. Returns 0 if the spritesheet relies on calculated frame counts, and + * the images have not been fully loaded. + * @method getNumFrames + * @param {String} animation The name of the animation to get a frame count for. + * @return {Number} The number of frames in the animation, or in the entire sprite sheet if the animation param is omitted. + */ + p.getNumFrames = function(animation) { + if (animation == null) { + return this._frames ? this._frames.length : this._numFrames || 0; + } else { + var data = this._data[animation]; + if (data == null) { return 0; } + else { return data.frames.length; } + } + }; + + /** + * Returns an object defining the specified animation. The returned object contains:
    + *
  • frames: an array of the frame ids in the animation
  • + *
  • speed: the playback speed for this animation
  • + *
  • name: the name of the animation
  • + *
  • next: the default animation to play next. If the animation loops, the name and next property will be the + * same.
  • + *
+ * @method getAnimation + * @param {String} name The name of the animation to get. + * @return {Object} a generic object with frames, speed, name, and next properties. + **/ + p.getAnimation = function(name) { + return this._data[name]; + }; + + /** + * Returns an object specifying the image and source rect of the specified frame. The returned object has:
    + *
  • an image property holding a reference to the image object in which the frame is found
  • + *
  • a rect property containing a Rectangle instance which defines the boundaries for the frame within that + * image.
  • + *
  • A regX and regY property corresponding to the regX/Y values for the frame. + *
+ * @method getFrame + * @param {Number} frameIndex The index of the frame. + * @return {Object} a generic object with image and rect properties. Returns null if the frame does not exist. + **/ + p.getFrame = function(frameIndex) { + var frame; + if (this._frames && (frame=this._frames[frameIndex])) { return frame; } + return null; + }; + + /** + * Returns a {{#crossLink "Rectangle"}}{{/crossLink}} instance defining the bounds of the specified frame relative + * to the origin. For example, a 90 x 70 frame with a regX of 50 and a regY of 40 would return: + * + * [x=-50, y=-40, width=90, height=70] + * + * @method getFrameBounds + * @param {Number} frameIndex The index of the frame. + * @param {Rectangle} [rectangle] A Rectangle instance to copy the values into. By default a new instance is created. + * @return {Rectangle} A Rectangle instance. Returns null if the frame does not exist, or the image is not fully loaded. + **/ + p.getFrameBounds = function(frameIndex, rectangle) { + var frame = this.getFrame(frameIndex); + return frame ? (rectangle||new createjs.Rectangle()).setValues(-frame.regX, -frame.regY, frame.rect.width, frame.rect.height) : null; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[SpriteSheet]"; + }; + + /** + * SpriteSheet cannot be cloned. A SpriteSheet can be shared by multiple Sprite instances without cloning it. + * @method clone + **/ + p.clone = function() { + throw("SpriteSheet cannot be cloned.") + }; + +// private methods: + /** + * @method _parseData + * @param {Object} data An object describing the SpriteSheet data. + * @protected + **/ + p._parseData = function(data) { + var i,l,o,a; + if (data == null) { return; } + + this.framerate = data.framerate||0; + + // parse images: + if (data.images && (l=data.images.length) > 0) { + a = this._images = []; + for (i=0; i= maxFrames) { break imgLoop; } + frameCount++; + this._frames.push({ + image: img, + rect: new createjs.Rectangle(x, y, frameWidth, frameHeight), + regX: this._regX, + regY: this._regY + }); + x += frameWidth+spacing; + } + y += frameHeight+spacing; + } + } + this._numFrames = frameCount; + }; + + + createjs.SpriteSheet = createjs.promote(SpriteSheet, "EventDispatcher"); +}()); +//############################################################################## +// Graphics.js +//############################################################################## - createjs.SpriteSheet = createjs.promote(SpriteSheet, "EventDispatcher"); +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * The Graphics class exposes an easy to use API for generating vector drawing instructions and drawing them to a + * specified context. Note that you can use Graphics without any dependency on the EaselJS framework by calling {{#crossLink "Graphics/draw"}}{{/crossLink}} + * directly, or it can be used with the {{#crossLink "Shape"}}{{/crossLink}} object to draw vector graphics within the + * context of an EaselJS display list. + * + * There are two approaches to working with Graphics object: calling methods on a Graphics instance (the "Graphics API"), or + * instantiating Graphics command objects and adding them to the graphics queue via {{#crossLink "Graphics/append"}}{{/crossLink}}. + * The former abstracts the latter, simplifying beginning and ending paths, fills, and strokes. + * + * var g = new createjs.Graphics(); + * g.setStrokeStyle(1); + * g.beginStroke("#000000"); + * g.beginFill("red"); + * g.drawCircle(0,0,30); + * + * All drawing methods in Graphics return the Graphics instance, so they can be chained together. For example, + * the following line of code would generate the instructions to draw a rectangle with a red stroke and blue fill: + * + * myGraphics.beginStroke("red").beginFill("blue").drawRect(20, 20, 100, 50); + * + * Each graphics API call generates a command object (see below). The last command to be created can be accessed via + * {{#crossLink "Graphics/command:property"}}{{/crossLink}}: + * + * var fillCommand = myGraphics.beginFill("red").command; + * // ... later, update the fill style/color: + * fillCommand.style = "blue"; + * // or change it to a bitmap fill: + * fillCommand.bitmap(myImage); + * + * For more direct control of rendering, you can instantiate and append command objects to the graphics queue directly. In this case, you + * need to manage path creation manually, and ensure that fill/stroke is applied to a defined path: + * + * // start a new path. Graphics.beginCmd is a reusable BeginPath instance: + * myGraphics.append(createjs.Graphics.beginCmd); + * // we need to define the path before applying the fill: + * var circle = new createjs.Graphics.Circle(0,0,30); + * myGraphics.append(circle); + * // fill the path we just defined: + * var fill = new createjs.Graphics.Fill("red"); + * myGraphics.append(fill); + * + * These approaches can be used together, for example to insert a custom command: + * + * myGraphics.beginFill("red"); + * var customCommand = new CustomSpiralCommand(etc); + * myGraphics.append(customCommand); + * myGraphics.beginFill("blue"); + * myGraphics.drawCircle(0, 0, 30); + * + * See {{#crossLink "Graphics/append"}}{{/crossLink}} for more info on creating custom commands. + * + *

Tiny API

+ * The Graphics class also includes a "tiny API", which is one or two-letter methods that are shortcuts for all of the + * Graphics methods. These methods are great for creating compact instructions, and is used by the Toolkit for CreateJS + * to generate readable code. All tiny methods are marked as protected, so you can view them by enabling protected + * descriptions in the docs. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
TinyMethodTinyMethod
mt{{#crossLink "Graphics/moveTo"}}{{/crossLink}} lt {{#crossLink "Graphics/lineTo"}}{{/crossLink}}
a/at{{#crossLink "Graphics/arc"}}{{/crossLink}} / {{#crossLink "Graphics/arcTo"}}{{/crossLink}} bt{{#crossLink "Graphics/bezierCurveTo"}}{{/crossLink}}
ea{{#crossLink "Graphics/ellipticalArc"}}{{/crossLink}} r{{#crossLink "Graphics/rect"}}{{/crossLink}}
qt{{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} (also curveTo)c{{#crossLink "Graphics/clear"}}{{/crossLink}}
cp{{#crossLink "Graphics/closePath"}}{{/crossLink}} lf{{#crossLink "Graphics/beginLinearGradientFill"}}{{/crossLink}}
f{{#crossLink "Graphics/beginFill"}}{{/crossLink}} bf{{#crossLink "Graphics/beginBitmapFill"}}{{/crossLink}}
rf{{#crossLink "Graphics/beginRadialGradientFill"}}{{/crossLink}} ss / sd{{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} / {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}}
ef{{#crossLink "Graphics/endFill"}}{{/crossLink}} ls{{#crossLink "Graphics/beginLinearGradientStroke"}}{{/crossLink}}
s{{#crossLink "Graphics/beginStroke"}}{{/crossLink}} bs{{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}}
rs{{#crossLink "Graphics/beginRadialGradientStroke"}}{{/crossLink}} dr{{#crossLink "Graphics/drawRect"}}{{/crossLink}}
es{{#crossLink "Graphics/endStroke"}}{{/crossLink}} rc{{#crossLink "Graphics/drawRoundRectComplex"}}{{/crossLink}}
rr{{#crossLink "Graphics/drawRoundRect"}}{{/crossLink}} de{{#crossLink "Graphics/drawEllipse"}}{{/crossLink}}
dc{{#crossLink "Graphics/drawCircle"}}{{/crossLink}} p{{#crossLink "Graphics/decodePath"}}{{/crossLink}}
dp{{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}}
+ * + * Here is the above example, using the tiny API instead. + * + * myGraphics.s("red").f("blue").r(20, 20, 100, 50); + * + * @class Graphics + * @constructor + **/ + function Graphics() { + + + // public properties + /** + * Holds a reference to the last command that was created or appended. For example, you could retain a reference + * to a Fill command in order to dynamically update the color later by using: + * + * var myFill = myGraphics.beginFill("red").command; + * // update color later: + * myFill.style = "yellow"; + * + * @property command + * @type Object + **/ + this.command = null; + + + // private properties + /** + * @property _stroke + * @protected + * @type {Stroke} + **/ + this._stroke = null; + + /** + * @property _strokeStyle + * @protected + * @type {StrokeStyle} + **/ + this._strokeStyle = null; + + /** + * @property _oldStrokeStyle + * @protected + * @type {StrokeStyle} + **/ + this._oldStrokeStyle = null; + + /** + * @property _strokeDash + * @protected + * @type {StrokeDash} + **/ + this._strokeDash = null; + + /** + * @property _oldStrokeDash + * @protected + * @type {StrokeDash} + **/ + this._oldStrokeDash = null; + + /** + * @property _strokeIgnoreScale + * @protected + * @type Boolean + **/ + this._strokeIgnoreScale = false; + + /** + * @property _fill + * @protected + * @type {Fill} + **/ + this._fill = null; + + /** + * @property _instructions + * @protected + * @type {Array} + **/ + this._instructions = []; + + /** + * Indicates the last instruction index that was committed. + * @property _commitIndex + * @protected + * @type {Number} + **/ + this._commitIndex = 0; + + /** + * Uncommitted instructions. + * @property _activeInstructions + * @protected + * @type {Array} + **/ + this._activeInstructions = []; + + /** + * This indicates that there have been changes to the activeInstruction list since the last updateInstructions call. + * @property _dirty + * @protected + * @type {Boolean} + * @default false + **/ + this._dirty = false; + + /** + * Index to draw from if a store operation has happened. + * @property _storeIndex + * @protected + * @type {Number} + * @default 0 + **/ + this._storeIndex = 0; + + // setup: + this.clear(); + } + var p = Graphics.prototype; + var G = Graphics; // shortcut + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// static public methods: + /** + * Returns a CSS compatible color string based on the specified RGB numeric color values in the format + * "rgba(255,255,255,1.0)", or if alpha is null then in the format "rgb(255,255,255)". For example, + * + * createjs.Graphics.getRGB(50, 100, 150, 0.5); + * // Returns "rgba(50,100,150,0.5)" + * + * It also supports passing a single hex color value as the first param, and an optional alpha value as the second + * param. For example, + * + * createjs.Graphics.getRGB(0xFF00FF, 0.2); + * // Returns "rgba(255,0,255,0.2)" + * + * @method getRGB + * @static + * @param {Number} r The red component for the color, between 0 and 0xFF (255). + * @param {Number} g The green component for the color, between 0 and 0xFF (255). + * @param {Number} b The blue component for the color, between 0 and 0xFF (255). + * @param {Number} [alpha] The alpha component for the color where 0 is fully transparent and 1 is fully opaque. + * @return {String} A CSS compatible color string based on the specified RGB numeric color values in the format + * "rgba(255,255,255,1.0)", or if alpha is null then in the format "rgb(255,255,255)". + **/ + Graphics.getRGB = function(r, g, b, alpha) { + if (r != null && b == null) { + alpha = g; + b = r&0xFF; + g = r>>8&0xFF; + r = r>>16&0xFF; + } + if (alpha == null) { + return "rgb("+r+","+g+","+b+")"; + } else { + return "rgba("+r+","+g+","+b+","+alpha+")"; + } + }; + + /** + * Returns a CSS compatible color string based on the specified HSL numeric color values in the format "hsla(360,100,100,1.0)", + * or if alpha is null then in the format "hsl(360,100,100)". + * + * createjs.Graphics.getHSL(150, 100, 70); + * // Returns "hsl(150,100,70)" + * + * @method getHSL + * @static + * @param {Number} hue The hue component for the color, between 0 and 360. + * @param {Number} saturation The saturation component for the color, between 0 and 100. + * @param {Number} lightness The lightness component for the color, between 0 and 100. + * @param {Number} [alpha] The alpha component for the color where 0 is fully transparent and 1 is fully opaque. + * @return {String} A CSS compatible color string based on the specified HSL numeric color values in the format + * "hsla(360,100,100,1.0)", or if alpha is null then in the format "hsl(360,100,100)". + **/ + Graphics.getHSL = function(hue, saturation, lightness, alpha) { + if (alpha == null) { + return "hsl("+(hue%360)+","+saturation+"%,"+lightness+"%)"; + } else { + return "hsla("+(hue%360)+","+saturation+"%,"+lightness+"%,"+alpha+")"; + } + }; + + +// static properties: + /** + * A reusable instance of {{#crossLink "Graphics/BeginPath"}}{{/crossLink}} to avoid + * unnecessary instantiation. + * @property beginCmd + * @type {Graphics.BeginPath} + * @static + **/ + // defined at the bottom of this file. + + /** + * Map of Base64 characters to values. Used by {{#crossLink "Graphics/decodePath"}}{{/crossLink}}. + * @property BASE_64 + * @static + * @final + * @readonly + * @type {Object} + **/ + Graphics.BASE_64 = {"A":0,"B":1,"C":2,"D":3,"E":4,"F":5,"G":6,"H":7,"I":8,"J":9,"K":10,"L":11,"M":12,"N":13,"O":14,"P":15,"Q":16,"R":17,"S":18,"T":19,"U":20,"V":21,"W":22,"X":23,"Y":24,"Z":25,"a":26,"b":27,"c":28,"d":29,"e":30,"f":31,"g":32,"h":33,"i":34,"j":35,"k":36,"l":37,"m":38,"n":39,"o":40,"p":41,"q":42,"r":43,"s":44,"t":45,"u":46,"v":47,"w":48,"x":49,"y":50,"z":51,"0":52,"1":53,"2":54,"3":55,"4":56,"5":57,"6":58,"7":59,"8":60,"9":61,"+":62,"/":63}; + + /** + * Maps numeric values for the caps parameter of {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} to + * corresponding string values. This is primarily for use with the tiny API. The mappings are as follows: 0 to + * "butt", 1 to "round", and 2 to "square". + * For example, to set the line caps to "square": + * + * myGraphics.ss(16, 2); + * + * @property STROKE_CAPS_MAP + * @static + * @final + * @readonly + * @type {Array} + **/ + Graphics.STROKE_CAPS_MAP = ["butt", "round", "square"]; + + /** + * Maps numeric values for the joints parameter of {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} to + * corresponding string values. This is primarily for use with the tiny API. The mappings are as follows: 0 to + * "miter", 1 to "round", and 2 to "bevel". + * For example, to set the line joints to "bevel": + * + * myGraphics.ss(16, 0, 2); + * + * @property STROKE_JOINTS_MAP + * @static + * @final + * @readonly + * @type {Array} + **/ + Graphics.STROKE_JOINTS_MAP = ["miter", "round", "bevel"]; + + /** + * @property _ctx + * @static + * @protected + * @type {CanvasRenderingContext2D} + **/ + var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); + if (canvas.getContext) { + Graphics._ctx = canvas.getContext("2d"); + canvas.width = canvas.height = 1; + } + + +// getter / setters: + /** + * Use the {{#crossLink "Graphics/instructions:property"}}{{/crossLink}} property instead. + * @method getInstructions + * @return {Array} + * @deprecated + **/ + p.getInstructions = function() { + this._updateInstructions(); + return this._instructions; + }; + + /** + * Returns the graphics instructions array. Each entry is a graphics command object (ex. Graphics.Fill, Graphics.Rect) + * Modifying the returned array directly is not recommended, and is likely to result in unexpected behaviour. + * + * This property is mainly intended for introspection of the instructions (ex. for graphics export). + * @property instructions + * @type {Array} + * @readonly + **/ + try { + Object.defineProperties(p, { + instructions: { get: p.getInstructions } + }); + } catch (e) {} + + +// public methods: + /** + * Returns true if this Graphics instance has no drawing commands. + * @method isEmpty + * @return {Boolean} Returns true if this Graphics instance has no drawing commands. + **/ + p.isEmpty = function() { + return !(this._instructions.length || this._activeInstructions.length); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Object} data Optional data that is passed to graphics command exec methods. When called from a Shape instance, the shape passes itself as the data parameter. This can be used by custom graphic commands to insert contextual data. + **/ + p.draw = function(ctx, data) { + this._updateInstructions(); + var instr = this._instructions; + for (var i=this._storeIndex, l=instr.length; iDisplayObject.mask to draw the clipping path, for example. + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method drawAsPath + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + **/ + p.drawAsPath = function(ctx) { + this._updateInstructions(); + var instr, instrs = this._instructions; + for (var i=this._storeIndex, l=instrs.length; i + * whatwg spec. + * @method lineTo + * @param {Number} x The x coordinate the drawing point should draw to. + * @param {Number} y The y coordinate the drawing point should draw to. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.lineTo = function(x, y) { + return this.append(new G.LineTo(x,y)); + }; + + /** + * Draws an arc with the specified control points and radius. For detailed information, read the + * + * whatwg spec. A tiny API method "at" also exists. + * @method arcTo + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} radius + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.arcTo = function(x1, y1, x2, y2, radius) { + return this.append(new G.ArcTo(x1, y1, x2, y2, radius)); + }; + + /** + * Draws an arc defined by the radius, startAngle and endAngle arguments, centered at the position (x, y). For + * example, to draw a full circle with a radius of 20 centered at (100, 100): + * + * arc(100, 100, 20, 0, Math.PI*2); + * + * For detailed information, read the + * whatwg spec. + * A tiny API method "a" also exists. + * @method arc + * @param {Number} x + * @param {Number} y + * @param {Number} radius + * @param {Number} startAngle Measured in radians. + * @param {Number} endAngle Measured in radians. + * @param {Boolean} anticlockwise + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.arc = function(x, y, radius, startAngle, endAngle, anticlockwise) { + return this.append(new G.Arc(x, y, radius, startAngle, endAngle, anticlockwise)); + }; + + /** + * Draws an elliptical arc defined by the radii rx and ry, startAngle and endAngle arguments, centered at the position (x, y). + * + * A tiny API method "ea" also exists. + * @method ellipticalArc + * @param {Number} x center X + * @param {Number} y center Y + * @param {Number} rx horizontal radius + * @param {Number} ry vertical radius + * @param {Number} startAngle Measured in radians. + * @param {Number} endAngle Measured in radians. + * @param {Boolean} anticlockwise if true, clockwise if false + * @param {String} closure omit for no closure (just an arc), 'radii' (makes a sector), 'chord' (makes a segment) + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.ellipticalArc = function(x, y, rx, ry, startAngle, endAngle, anticlockwise, closure) { + return this.append(new G.EllipticalArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, closure)); + } + + + /** + * Draws a quadratic curve from the current drawing point to (x, y) using the control point (cpx, cpy). For detailed + * information, read the + * whatwg spec. A tiny API method "qt" also exists. + * @method quadraticCurveTo + * @param {Number} cpx + * @param {Number} cpy + * @param {Number} x + * @param {Number} y + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.quadraticCurveTo = function(cpx, cpy, x, y) { + return this.append(new G.QuadraticCurveTo(cpx, cpy, x, y)); + }; + + /** + * Draws a bezier curve from the current drawing point to (x, y) using the control points (cp1x, cp1y) and (cp2x, + * cp2y). For detailed information, read the + * + * whatwg spec. A tiny API method "bt" also exists. + * @method bezierCurveTo + * @param {Number} cp1x + * @param {Number} cp1y + * @param {Number} cp2x + * @param {Number} cp2y + * @param {Number} x + * @param {Number} y + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { + return this.append(new G.BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)); + }; + + /** + * Draws a rectangle at (x, y) with the specified width and height using the current fill and/or stroke. + * For detailed information, read the + * + * whatwg spec. A tiny API method "r" also exists. + * @method rect + * @param {Number} x + * @param {Number} y + * @param {Number} w Width of the rectangle + * @param {Number} h Height of the rectangle + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.rect = function(x, y, w, h) { + return this.append(new G.Rect(x, y, w, h)); + }; + + /** + * Closes the current path, effectively drawing a line from the current drawing point to the first drawing point specified + * since the fill or stroke was last set. A tiny API method "cp" also exists. + * @method closePath + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.closePath = function() { + return this._activeInstructions.length ? this.append(new G.ClosePath()) : this; + }; + + +// public methods that roughly map to Flash graphics APIs: + /** + * Clears all drawing instructions, effectively resetting this Graphics instance. Any line and fill styles will need + * to be redefined to draw shapes following a clear call. A tiny API method "c" also exists. + * @method clear + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.clear = function() { + this._instructions.length = this._activeInstructions.length = this._commitIndex = 0; + this._strokeStyle = this._oldStrokeStyle = this._stroke = this._fill = this._strokeDash = this._oldStrokeDash = null; + this._dirty = this._strokeIgnoreScale = false; + return this; + }; + + /** + * Begins a fill with the specified color. This ends the current sub-path. A tiny API method "f" also exists. + * @method beginFill + * @param {String} color A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to + * null will result in no fill. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginFill = function(color) { + return this._setFill(color ? new G.Fill(color) : null); + }; + + /** + * Begins a linear gradient fill defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For + * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a + * square to display it: + * + * myGraphics.beginLinearGradientFill(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120); + * + * A tiny API method "lf" also exists. + * @method beginLinearGradientFill + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient + * drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw + * the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. + * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginLinearGradientFill = function(colors, ratios, x0, y0, x1, y1) { + return this._setFill(new G.Fill().linearGradient(colors, ratios, x0, y0, x1, y1)); + }; + + /** + * Begins a radial gradient fill. This ends the current sub-path. For example, the following code defines a red to + * blue radial gradient centered at (100, 100), with a radius of 50, and draws a circle to display it: + * + * myGraphics.beginRadialGradientFill(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50).drawCircle(100, 100, 50); + * + * A tiny API method "rf" also exists. + * @method beginRadialGradientFill + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 Center position of the inner circle that defines the gradient. + * @param {Number} y0 Center position of the inner circle that defines the gradient. + * @param {Number} r0 Radius of the inner circle that defines the gradient. + * @param {Number} x1 Center position of the outer circle that defines the gradient. + * @param {Number} y1 Center position of the outer circle that defines the gradient. + * @param {Number} r1 Radius of the outer circle that defines the gradient. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginRadialGradientFill = function(colors, ratios, x0, y0, r0, x1, y1, r1) { + return this._setFill(new G.Fill().radialGradient(colors, ratios, x0, y0, r0, x1, y1, r1)); + }; + + /** + * Begins a pattern fill using the specified image. This ends the current sub-path. A tiny API method "bf" also + * exists. + * @method beginBitmapFill + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use + * as the pattern. Must be loaded prior to creating a bitmap fill, or the fill will be empty. + * @param {String} repetition Optional. Indicates whether to repeat the image in the fill area. One of "repeat", + * "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". Note that Firefox does not support "repeat-x" or + * "repeat-y" (latest tests were in FF 20.0), and will default to "repeat". + * @param {Matrix2D} matrix Optional. Specifies a transformation matrix for the bitmap fill. This transformation + * will be applied relative to the parent transform. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginBitmapFill = function(image, repetition, matrix) { + return this._setFill(new G.Fill(null,matrix).bitmap(image, repetition)); + }; + + /** + * Ends the current sub-path, and begins a new one with no fill. Functionally identical to beginFill(null). + * A tiny API method "ef" also exists. + * @method endFill + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.endFill = function() { + return this.beginFill(); + }; + + /** + * Sets the stroke style. Like all drawing methods, this can be chained, so you can define + * the stroke style and color in a single line of code like so: + * + * myGraphics.setStrokeStyle(8,"round").beginStroke("#F00"); + * + * A tiny API method "ss" also exists. + * @method setStrokeStyle + * @param {Number} thickness The width of the stroke. + * @param {String | Number} [caps=0] Indicates the type of caps to use at the end of lines. One of butt, + * round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with + * the tiny API. + * @param {String | Number} [joints=0] Specifies the type of joints that should be used where two lines meet. + * One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel) + * for use with the tiny API. + * @param {Number} [miterLimit=10] If joints is set to "miter", then you can specify a miter limit ratio which + * controls at what point a mitered joint will be clipped. + * @param {Boolean} [ignoreScale=false] If true, the stroke will be drawn at the specified thickness regardless + * of active transformations. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.setStrokeStyle = function(thickness, caps, joints, miterLimit, ignoreScale) { + this._updateInstructions(true); + this._strokeStyle = this.command = new G.StrokeStyle(thickness, caps, joints, miterLimit, ignoreScale); + + // ignoreScale lives on Stroke, not StrokeStyle, so we do a little trickery: + if (this._stroke) { this._stroke.ignoreScale = ignoreScale; } + this._strokeIgnoreScale = ignoreScale; + return this; + }; + + /** + * Sets or clears the stroke dash pattern. + * + * myGraphics.setStrokeDash([20, 10], 0); + * + * A tiny API method `sd` also exists. + * @method setStrokeDash + * @param {Array} [segments] An array specifying the dash pattern, alternating between line and gap. + * For example, `[20,10]` would create a pattern of 20 pixel lines with 10 pixel gaps between them. + * Passing null or an empty array will clear the existing stroke dash. + * @param {Number} [offset=0] The offset of the dash pattern. For example, you could increment this value to create a "marching ants" effect. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.setStrokeDash = function(segments, offset) { + this._updateInstructions(true); + this._strokeDash = this.command = new G.StrokeDash(segments, offset); + return this; + }; + + /** + * Begins a stroke with the specified color. This ends the current sub-path. A tiny API method "s" also exists. + * @method beginStroke + * @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to + * null will result in no stroke. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginStroke = function(color) { + return this._setStroke(color ? new G.Stroke(color) : null); + }; + + /** + * Begins a linear gradient stroke defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For + * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a + * square to display it: + * + * myGraphics.setStrokeStyle(10). + * beginLinearGradientStroke(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120); + * + * A tiny API method "ls" also exists. + * @method beginLinearGradientStroke + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. + * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginLinearGradientStroke = function(colors, ratios, x0, y0, x1, y1) { + return this._setStroke(new G.Stroke().linearGradient(colors, ratios, x0, y0, x1, y1)); + }; + + /** + * Begins a radial gradient stroke. This ends the current sub-path. For example, the following code defines a red to + * blue radial gradient centered at (100, 100), with a radius of 50, and draws a rectangle to display it: + * + * myGraphics.setStrokeStyle(10) + * .beginRadialGradientStroke(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50) + * .drawRect(50, 90, 150, 110); + * + * A tiny API method "rs" also exists. + * @method beginRadialGradientStroke + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%, then draw the second color + * to 100%. + * @param {Number} x0 Center position of the inner circle that defines the gradient. + * @param {Number} y0 Center position of the inner circle that defines the gradient. + * @param {Number} r0 Radius of the inner circle that defines the gradient. + * @param {Number} x1 Center position of the outer circle that defines the gradient. + * @param {Number} y1 Center position of the outer circle that defines the gradient. + * @param {Number} r1 Radius of the outer circle that defines the gradient. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginRadialGradientStroke = function(colors, ratios, x0, y0, r0, x1, y1, r1) { + return this._setStroke(new G.Stroke().radialGradient(colors, ratios, x0, y0, r0, x1, y1, r1)); + }; + + /** + * Begins a pattern fill using the specified image. This ends the current sub-path. Note that unlike bitmap fills, + * strokes do not currently support a matrix parameter due to limitations in the canvas API. A tiny API method "bs" + * also exists. + * @method beginBitmapStroke + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use + * as the pattern. Must be loaded prior to creating a bitmap fill, or the fill will be empty. + * @param {String} [repetition=repeat] Optional. Indicates whether to repeat the image in the fill area. One of + * "repeat", "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.beginBitmapStroke = function(image, repetition) { + // NOTE: matrix is not supported for stroke because transforms on strokes also affect the drawn stroke width. + return this._setStroke(new G.Stroke().bitmap(image, repetition)); + }; + + /** + * Ends the current sub-path, and begins a new one with no stroke. Functionally identical to beginStroke(null). + * A tiny API method "es" also exists. + * @method endStroke + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.endStroke = function() { + return this.beginStroke(); + }; + + /** + * Maps the familiar ActionScript curveTo() method to the functionally similar {{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} + * method. + * @method quadraticCurveTo + * @param {Number} cpx + * @param {Number} cpy + * @param {Number} x + * @param {Number} y + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.curveTo = p.quadraticCurveTo; + + /** + * + * Maps the familiar ActionScript drawRect() method to the functionally similar {{#crossLink "Graphics/rect"}}{{/crossLink}} + * method. + * @method drawRect + * @param {Number} x + * @param {Number} y + * @param {Number} w Width of the rectangle + * @param {Number} h Height of the rectangle + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawRect = p.rect; + + /** + * Draws a rounded rectangle with all corners with the specified radius. + * @method drawRoundRect + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + * @param {Number} radius Corner radius. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawRoundRect = function(x, y, w, h, radius) { + return this.drawRoundRectComplex(x, y, w, h, radius, radius, radius, radius); + }; + + /** + * Draws a rounded rectangle with different corner radii. Supports positive and negative corner radii. A tiny API + * method "rc" also exists. + * @method drawRoundRectComplex + * @param {Number} x The horizontal coordinate to draw the round rect. + * @param {Number} y The vertical coordinate to draw the round rect. + * @param {Number} w The width of the round rect. + * @param {Number} h The height of the round rect. + * @param {Number} radiusTL Top left corner radius. + * @param {Number} radiusTR Top right corner radius. + * @param {Number} radiusBR Bottom right corner radius. + * @param {Number} radiusBL Bottom left corner radius. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawRoundRectComplex = function(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL) { + return this.append(new G.RoundRect(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL)); + }; + + /** + * Draws a circle with the specified radius at (x, y). + * + * var g = new createjs.Graphics(); + * g.setStrokeStyle(1); + * g.beginStroke(createjs.Graphics.getRGB(0,0,0)); + * g.beginFill(createjs.Graphics.getRGB(255,0,0)); + * g.drawCircle(0,0,3); + * + * var s = new createjs.Shape(g); + * s.x = 100; + * s.y = 100; + * + * stage.addChild(s); + * stage.update(); + * + * A tiny API method "dc" also exists. + * @method drawCircle + * @param {Number} x x coordinate center point of circle. + * @param {Number} y y coordinate center point of circle. + * @param {Number} radius Radius of circle. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawCircle = function(x, y, radius) { + return this.append(new G.Circle(x, y, radius)); + }; + + /** + * Draws an ellipse (oval) with a specified width (w) and height (h). Similar to {{#crossLink "Graphics/drawCircle"}}{{/crossLink}}, + * except the width and height can be different. A tiny API method "de" also exists. + * @method drawEllipse + * @param {Number} x The left coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * which draws from center. + * @param {Number} y The top coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * which draws from the center. + * @param {Number} w The height (horizontal diameter) of the ellipse. The horizontal radius will be half of this + * number. + * @param {Number} h The width (vertical diameter) of the ellipse. The vertical radius will be half of this number. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawEllipse = function(x, y, w, h) { + return this.append(new G.Ellipse(x, y, w, h)); + }; + + /** + * Draws a star if pointSize is greater than 0, or a regular polygon if pointSize is 0 with the specified number of + * points. For example, the following code will draw a familiar 5 pointed star shape centered at 100, 100 and with a + * radius of 50: + * + * myGraphics.beginFill("#FF0").drawPolyStar(100, 100, 50, 5, 0.6, -90); + * // Note: -90 makes the first point vertical + * + * A tiny API method "dp" also exists. + * + * @method drawPolyStar + * @param {Number} x Position of the center of the shape. + * @param {Number} y Position of the center of the shape. + * @param {Number} radius The outer radius of the shape. + * @param {Number} sides The number of points on the star or sides on the polygon. + * @param {Number} pointSize The depth or "pointy-ness" of the star points. A pointSize of 0 will draw a regular + * polygon (no points), a pointSize of 1 will draw nothing because the points are infinitely pointy. + * @param {Number} angle The angle of the first point / corner. For example a value of 0 will draw the first point + * directly to the right of the center. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.drawPolyStar = function(x, y, radius, sides, pointSize, angle) { + return this.append(new G.PolyStar(x, y, radius, sides, pointSize, angle)); + }; + + // TODO: deprecated. + /** + * Removed in favour of using custom command objects with {{#crossLink "Graphics/append"}}{{/crossLink}}. + * @method inject + * @deprecated + **/ + + /** + * Appends a graphics command object to the graphics queue. Command objects expose an "exec" method + * that accepts two parameters: the Context2D to operate on, and an arbitrary data object passed into + * {{#crossLink "Graphics/draw"}}{{/crossLink}}. The latter will usually be the Shape instance that called draw. + * + * This method is used internally by Graphics methods, such as drawCircle, but can also be used directly to insert + * built-in or custom graphics commands. For example: + * + * // attach data to our shape, so we can access it during the draw: + * myShape.color = "red"; + * + * // append a Circle command object: + * myShape.graphics.append(new createjs.Graphics.Circle(50, 50, 30)); + * + * // append a custom command object with an exec method that sets the fill style + * // based on the shape's data, and then fills the circle. + * myShape.graphics.append({exec:function(ctx, shape) { + * ctx.fillStyle = shape.color; + * ctx.fill(); + * }}); + * + * @method append + * @param {Object} command A graphics command object exposing an "exec" method. + * @param {boolean} clean The clean param is primarily for internal use. A value of true indicates that a command does not generate a path that should be stroked or filled. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.append = function(command, clean) { + this._activeInstructions.push(command); + this.command = command; + if (!clean) { this._dirty = true; } + return this; + }; + + /** + * Decodes a compact encoded path string into a series of draw instructions. + * This format is not intended to be human readable, and is meant for use by authoring tools. + * The format uses a base64 character set, with each character representing 6 bits, to define a series of draw + * commands. + * + * Each command is comprised of a single "header" character followed by a variable number of alternating x and y + * position values. Reading the header bits from left to right (most to least significant): bits 1 to 3 specify the + * type of operation (0-moveTo, 1-lineTo, 2-quadraticCurveTo, 3-bezierCurveTo, 4-closePath, 5-7 unused). Bit 4 + * indicates whether position values use 12 bits (2 characters) or 18 bits (3 characters), with a one indicating the + * latter. Bits 5 and 6 are currently unused. + * + * Following the header is a series of 0 (closePath), 2 (moveTo, lineTo), 4 (quadraticCurveTo), or 6 (bezierCurveTo) + * parameters. These parameters are alternating x/y positions represented by 2 or 3 characters (as indicated by the + * 4th bit in the command char). These characters consist of a 1 bit sign (1 is negative, 0 is positive), followed + * by an 11 (2 char) or 17 (3 char) bit integer value. All position values are in tenths of a pixel. Except in the + * case of move operations which are absolute, this value is a delta from the previous x or y position (as + * appropriate). + * + * For example, the string "A3cAAMAu4AAA" represents a line starting at -150,0 and ending at 150,0. + *
A - bits 000000. First 3 bits (000) indicate a moveTo operation. 4th bit (0) indicates 2 chars per + * parameter. + *
n0 - 110111011100. Absolute x position of -150.0px. First bit indicates a negative value, remaining bits + * indicate 1500 tenths of a pixel. + *
AA - 000000000000. Absolute y position of 0. + *
I - 001100. First 3 bits (001) indicate a lineTo operation. 4th bit (1) indicates 3 chars per parameter. + *
Au4 - 000000101110111000. An x delta of 300.0px, which is added to the previous x value of -150.0px to + * provide an absolute position of +150.0px. + *
AAA - 000000000000000000. A y delta value of 0. + * + * A tiny API method "p" also exists. + * @method decodePath + * @param {String} str The path string to decode. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.decodePath = function(str) { + var instructions = [this.moveTo, this.lineTo, this.quadraticCurveTo, this.bezierCurveTo, this.closePath]; + var paramCount = [2, 2, 4, 6, 0]; + var i=0, l=str.length; + var params = []; + var x=0, y=0; + var base64 = Graphics.BASE_64; + + while (i>3; // highest order bits 1-3 code for operation. + var f = instructions[fi]; + // check that we have a valid instruction & that the unused bits are empty: + if (!f || (n&3)) { throw("bad path data (@"+i+"): "+c); } + var pl = paramCount[fi]; + if (!fi) { x=y=0; } // move operations reset the position. + params.length = 0; + i++; + var charCount = (n>>2&1)+2; // 4th header bit indicates number size for this operation. + for (var p=0; p>5) ? -1 : 1; + num = ((num&31)<<6)|(base64[str.charAt(i+1)]); + if (charCount == 3) { num = (num<<6)|(base64[str.charAt(i+2)]); } + num = sign*num/10; + if (p%2) { x = (num += x); } + else { y = (num += y); } + params[p] = num; + i += charCount; + } + f.apply(this,params); + } + return this; + }; + + /** + * Stores all graphics commands so they won't be executed in future draws. Calling store() a second time adds to + * the existing store. This also affects `drawAsPath()`. + * + * This is useful in cases where you are creating vector graphics in an iterative manner (ex. generative art), so + * that only new graphics need to be drawn (which can provide huge performance benefits), but you wish to retain all + * of the vector instructions for later use (ex. scaling, modifying, or exporting). + * + * Note that calling store() will force the active path (if any) to be ended in a manner similar to changing + * the fill or stroke. + * + * For example, consider a application where the user draws lines with the mouse. As each line segment (or collection of + * segments) are added to a Shape, it can be rasterized using {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}}, + * and then stored, so that it can be redrawn at a different scale when the application is resized, or exported to SVG. + * + * // set up cache: + * myShape.cache(0,0,500,500,scale); + * + * // when the user drags, draw a new line: + * myShape.graphics.moveTo(oldX,oldY).lineTo(newX,newY); + * // then draw it into the existing cache: + * myShape.updateCache("source-over"); + * // store the new line, so it isn't redrawn next time: + * myShape.store(); + * + * // then, when the window resizes, we can re-render at a different scale: + * // first, unstore all our lines: + * myShape.unstore(); + * // then cache using the new scale: + * myShape.cache(0,0,500,500,newScale); + * // finally, store the existing commands again: + * myShape.store(); + * + * @method store + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.store = function() { + this._updateInstructions(true); + this._storeIndex = this._instructions.length; + return this; + }; + + /** + * Unstores any graphics commands that were previously stored using {{#crossLink "Graphics/store"}}{{/crossLink}} + * so that they will be executed in subsequent draw calls. + * + * @method unstore + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.unstore = function() { + this._storeIndex = 0; + return this; + }; + + /** + * Returns a clone of this Graphics instance. Note that the individual command objects are not cloned. + * @method clone + * @return {Graphics} A clone of the current Graphics instance. + **/ + p.clone = function() { + var o = new Graphics(); + o.command = this.command; + o._stroke = this._stroke; + o._strokeStyle = this._strokeStyle; + o._strokeDash = this._strokeDash; + o._strokeIgnoreScale = this._strokeIgnoreScale; + o._fill = this._fill; + o._instructions = this._instructions.slice(); + o._commitIndex = this._commitIndex; + o._activeInstructions = this._activeInstructions.slice(); + o._dirty = this._dirty; + o._storeIndex = this._storeIndex; + return o; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Graphics]"; + }; + + +// tiny API: + /** + * Shortcut to moveTo. + * @method mt + * @param {Number} x The x coordinate the drawing point should move to. + * @param {Number} y The y coordinate the drawing point should move to. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls). + * @chainable + * @protected + **/ + p.mt = p.moveTo; + + /** + * Shortcut to lineTo. + * @method lt + * @param {Number} x The x coordinate the drawing point should draw to. + * @param {Number} y The y coordinate the drawing point should draw to. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.lt = p.lineTo; + + /** + * Shortcut to arcTo. + * @method at + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} x2 + * @param {Number} y2 + * @param {Number} radius + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.at = p.arcTo; + + /** + * Shortcut to bezierCurveTo. + * @method bt + * @param {Number} cp1x + * @param {Number} cp1y + * @param {Number} cp2x + * @param {Number} cp2y + * @param {Number} x + * @param {Number} y + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.bt = p.bezierCurveTo; + + /** + * Shortcut to quadraticCurveTo / curveTo. + * @method qt + * @param {Number} cpx + * @param {Number} cpy + * @param {Number} x + * @param {Number} y + * @protected + * @chainable + **/ + p.qt = p.quadraticCurveTo; + + /** + * Shortcut to arc. + * @method a + * @param {Number} x + * @param {Number} y + * @param {Number} radius + * @param {Number} startAngle Measured in radians. + * @param {Number} endAngle Measured in radians. + * @param {Boolean} anticlockwise + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @protected + * @chainable + **/ + p.a = p.arc; + + /** + * Shortcut to ellipticalArc. + * @method ea + * @param {Number} x + * @param {Number} y + * @param {Number} rx + * @param {Number} ry + * @param {Number} startAngle Measured in radians. + * @param {Number} endAngle Measured in radians. + * @param {Boolean} anticlockwise + * @param {String} closure omit for no closure (just an arc), 'radii' (makes a sector), 'chord' (makes a segment) + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @protected + * @chainable + **/ + p.ea = p.ellipticalArc; + + /** + * Shortcut to rect. + * @method r + * @param {Number} x + * @param {Number} y + * @param {Number} w Width of the rectangle + * @param {Number} h Height of the rectangle + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.r = p.rect; + + /** + * Shortcut to closePath. + * @method cp + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.cp = p.closePath; + + /** + * Shortcut to clear. + * @method c + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.c = p.clear; + + /** + * Shortcut to beginFill. + * @method f + * @param {String} color A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to + * null will result in no fill. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.f = p.beginFill; + + /** + * Shortcut to beginLinearGradientFill. + * @method lf + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient + * drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw + * the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. + * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.lf = p.beginLinearGradientFill; + + /** + * Shortcut to beginRadialGradientFill. + * @method rf + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 Center position of the inner circle that defines the gradient. + * @param {Number} y0 Center position of the inner circle that defines the gradient. + * @param {Number} r0 Radius of the inner circle that defines the gradient. + * @param {Number} x1 Center position of the outer circle that defines the gradient. + * @param {Number} y1 Center position of the outer circle that defines the gradient. + * @param {Number} r1 Radius of the outer circle that defines the gradient. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.rf = p.beginRadialGradientFill; + + /** + * Shortcut to beginBitmapFill. + * @method bf + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use + * as the pattern. + * @param {String} repetition Optional. Indicates whether to repeat the image in the fill area. One of "repeat", + * "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". Note that Firefox does not support "repeat-x" or + * "repeat-y" (latest tests were in FF 20.0), and will default to "repeat". + * @param {Matrix2D} matrix Optional. Specifies a transformation matrix for the bitmap fill. This transformation + * will be applied relative to the parent transform. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.bf = p.beginBitmapFill; + + /** + * Shortcut to endFill. + * @method ef + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.ef = p.endFill; + + /** + * Shortcut to setStrokeStyle. + * @method ss + * @param {Number} thickness The width of the stroke. + * @param {String | Number} [caps=0] Indicates the type of caps to use at the end of lines. One of butt, + * round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with + * the tiny API. + * @param {String | Number} [joints=0] Specifies the type of joints that should be used where two lines meet. + * One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel) + * for use with the tiny API. + * @param {Number} [miterLimit=10] If joints is set to "miter", then you can specify a miter limit ratio which + * controls at what point a mitered joint will be clipped. + * @param {Boolean} [ignoreScale=false] If true, the stroke will be drawn at the specified thickness regardless + * of active transformations. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.ss = p.setStrokeStyle; + + /** + * Shortcut to setStrokeDash. + * @method sd + * @param {Array} [segments] An array specifying the dash pattern, alternating between line and gap. + * For example, [20,10] would create a pattern of 20 pixel lines with 10 pixel gaps between them. + * Passing null or an empty array will clear any existing dash. + * @param {Number} [offset=0] The offset of the dash pattern. For example, you could increment this value to create a "marching ants" effect. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.sd = p.setStrokeDash; + + /** + * Shortcut to beginStroke. + * @method s + * @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to + * null will result in no stroke. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.s = p.beginStroke; + + /** + * Shortcut to beginLinearGradientStroke. + * @method ls + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. + * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. + * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. + * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.ls = p.beginLinearGradientStroke; + + /** + * Shortcut to beginRadialGradientStroke. + * @method rs + * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define + * a gradient drawing from red to blue. + * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, + * 0.9] would draw the first color to 10% then interpolating to the second color at 90%, then draw the second color + * to 100%. + * @param {Number} x0 Center position of the inner circle that defines the gradient. + * @param {Number} y0 Center position of the inner circle that defines the gradient. + * @param {Number} r0 Radius of the inner circle that defines the gradient. + * @param {Number} x1 Center position of the outer circle that defines the gradient. + * @param {Number} y1 Center position of the outer circle that defines the gradient. + * @param {Number} r1 Radius of the outer circle that defines the gradient. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.rs = p.beginRadialGradientStroke; + + /** + * Shortcut to beginBitmapStroke. + * @method bs + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use + * as the pattern. + * @param {String} [repetition=repeat] Optional. Indicates whether to repeat the image in the fill area. One of + * "repeat", "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.bs = p.beginBitmapStroke; + + /** + * Shortcut to endStroke. + * @method es + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.es = p.endStroke; + + /** + * Shortcut to drawRect. + * @method dr + * @param {Number} x + * @param {Number} y + * @param {Number} w Width of the rectangle + * @param {Number} h Height of the rectangle + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.dr = p.drawRect; + + /** + * Shortcut to drawRoundRect. + * @method rr + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + * @param {Number} radius Corner radius. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.rr = p.drawRoundRect; + + /** + * Shortcut to drawRoundRectComplex. + * @method rc + * @param {Number} x The horizontal coordinate to draw the round rect. + * @param {Number} y The vertical coordinate to draw the round rect. + * @param {Number} w The width of the round rect. + * @param {Number} h The height of the round rect. + * @param {Number} radiusTL Top left corner radius. + * @param {Number} radiusTR Top right corner radius. + * @param {Number} radiusBR Bottom right corner radius. + * @param {Number} radiusBL Bottom left corner radius. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.rc = p.drawRoundRectComplex; + + /** + * Shortcut to drawCircle. + * @method dc + * @param {Number} x x coordinate center point of circle. + * @param {Number} y y coordinate center point of circle. + * @param {Number} radius Radius of circle. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.dc = p.drawCircle; + + /** + * Shortcut to drawEllipse. + * @method de + * @param {Number} x The left coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * which draws from center. + * @param {Number} y The top coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * which draws from the center. + * @param {Number} w The height (horizontal diameter) of the ellipse. The horizontal radius will be half of this + * number. + * @param {Number} h The width (vertical diameter) of the ellipse. The vertical radius will be half of this number. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.de = p.drawEllipse; + + /** + * Shortcut to drawPolyStar. + * @method dp + * @param {Number} x Position of the center of the shape. + * @param {Number} y Position of the center of the shape. + * @param {Number} radius The outer radius of the shape. + * @param {Number} sides The number of points on the star or sides on the polygon. + * @param {Number} pointSize The depth or "pointy-ness" of the star points. A pointSize of 0 will draw a regular + * polygon (no points), a pointSize of 1 will draw nothing because the points are infinitely pointy. + * @param {Number} angle The angle of the first point / corner. For example a value of 0 will draw the first point + * directly to the right of the center. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.dp = p.drawPolyStar; + + /** + * Shortcut to decodePath. + * @method p + * @param {String} str The path string to decode. + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + * @protected + **/ + p.p = p.decodePath; + + +// private methods: + /** + * @method _updateInstructions + * @param commit + * @protected + **/ + p._updateInstructions = function(commit) { + var instr = this._instructions, active = this._activeInstructions, commitIndex = this._commitIndex; + + if (this._dirty && active.length) { + instr.length = commitIndex; // remove old, uncommitted commands + instr.push(Graphics.beginCmd); + + var l = active.length, ll = instr.length; + instr.length = ll+l; + for (var i=0; i 0 && sina > 0) { + retval = Math.atan(tana); + } + else if (cosa < 0 && sina > 0) { + retval = Math.PI + Math.atan(tana); + } + else if (cosa < 0 && sina < 0) { + retval = Math.PI + Math.atan(tana); + } + else if (cosa > 0 && sina < 0) { + retval = 2 * Math.PI + Math.atan(tana); + } + + return retval; + } + + // This is just a copy of mathjs.equal, or rather mathjs.nearlyEqual + // For some reason can't use mathjs here + // But, perhaps this is better as it is self-contained and won't introduce a dependency in EaselJS on mathjs + // and also, the mathjs version is too stingy on its epsilon + function equalEnough(x, y) { + var relEpsilon = 0.001; + var absEpsilon = 2.2204460492503130808472633361816E-16; + + if (x === y) { + return true; + } + + // NaN + if (isNaN(x) || isNaN(y)) { + return false; + } + + // at this point x and y should be finite + if (isFinite(x) && isFinite(y)) { + // check numbers are very close, needed when comparing numbers near zero + var diff = Math.abs(x - y); + if (diff < absEpsilon) { + return true; + } + else { + // use relative error + return diff <= Math.max(Math.abs(x), Math.abs(y)) * relEpsilon; + } + } + + // Infinite and Number or negative Infinite and positive Infinite cases + return false; + } + + /** + * End support functions for elliptical arc + **/ + + /** + * Graphics command object. See {{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class QuadraticCurveTo + * @constructor + * @param {Number} cpx + * @param {Number} cpy + * @param {Number} x + * @param {Number} y + **/ + /** + * @property cpx + * @type Number + */ + /** + * @property cpy + * @type Number + */ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.QuadraticCurveTo = function(cpx, cpy, x, y) { + this.cpx = cpx; this.cpy = cpy; + this.x = x; this.y = y; + }).prototype.exec = function(ctx) { ctx.quadraticCurveTo(this.cpx, this.cpy, this.x, this.y); }; + + /** + * Graphics command object. See {{#crossLink "Graphics/bezierCurveTo"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class BezierCurveTo + * @constructor + * @param {Number} cp1x + * @param {Number} cp1y + * @param {Number} cp2x + * @param {Number} cp2y + * @param {Number} x + * @param {Number} y + **/ + /** + * @property cp1x + * @type Number + */ + /** + * @property cp1y + * @type Number + */ + /** + * @property cp2x + * @type Number + */ + /** + * @property cp2y + * @type Number + */ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.BezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { + this.cp1x = cp1x; this.cp1y = cp1y; + this.cp2x = cp2x; this.cp2y = cp2y; + this.x = x; this.y = y; + }).prototype.exec = function(ctx) { ctx.bezierCurveTo(this.cp1x, this.cp1y, this.cp2x, this.cp2y, this.x, this.y); }; + + /** + * Graphics command object. See {{#crossLink "Graphics/rect"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class Rect + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property w + * @type Number + */ + /** + * @property h + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.Rect = function(x, y, w, h) { + this.x = x; this.y = y; + this.w = w; this.h = h; + }).prototype.exec = function(ctx) { ctx.rect(this.x, this.y, this.w, this.h); }; + + /** + * Graphics command object. See {{#crossLink "Graphics/closePath"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class ClosePath + * @constructor + **/ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.ClosePath = function() { + }).prototype.exec = function(ctx) { ctx.closePath(); }; + + /** + * Graphics command object to begin a new path. See {{#crossLink "Graphics"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class BeginPath + * @constructor + **/ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.BeginPath = function() { + }).prototype.exec = function(ctx) { ctx.beginPath(); }; + + /** + * Graphics command object. See {{#crossLink "Graphics/beginFill"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class Fill + * @constructor + * @param {Object} style A valid Context2D fillStyle. + * @param {Matrix2D} matrix + **/ + /** + * A valid Context2D fillStyle. + * @property style + * @type Object + */ + /** + * @property matrix + * @type Matrix2D + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + p = (G.Fill = function(style, matrix) { + this.style = style; + this.matrix = matrix; + }).prototype; + p.exec = function(ctx) { + if (!this.style) { return; } + ctx.fillStyle = this.style; + var mtx = this.matrix; + if (mtx) { ctx.save(); ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty); } + ctx.fill(); + if (mtx) { ctx.restore(); } + }; + /** + * Creates a linear gradient style and assigns it to {{#crossLink "Fill/style:property"}}{{/crossLink}}. + * See {{#crossLink "Graphics/beginLinearGradientFill"}}{{/crossLink}} for more information. + * @method linearGradient + * @param {Array} colors + * + * @param {Array} ratios + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} x1 + * @param {Number} y1 + * @return {Fill} Returns this Fill object for chaining or assignment. + */ + p.linearGradient = function(colors, ratios, x0, y0, x1, y1) { + var o = this.style = Graphics._ctx.createLinearGradient(x0, y0, x1, y1); + for (var i=0, l=colors.length; i= 2) { + var o = this.style = Graphics._ctx.createPattern(image, repetition || ""); + o.props = {image: image, repetition: repetition, type: "bitmap"}; + } + return this; + }; + p.path = false; + + /** + * Graphics command object. See {{#crossLink "Graphics/beginStroke"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class Stroke + * @constructor + * @param {Object} style A valid Context2D fillStyle. + * @param {Boolean} ignoreScale + **/ + /** + * A valid Context2D strokeStyle. + * @property style + * @type Object + */ + /** + * @property ignoreScale + * @type Boolean + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + p = (G.Stroke = function(style, ignoreScale) { + this.style = style; + this.ignoreScale = ignoreScale; + }).prototype; + p.exec = function(ctx) { + if (!this.style) { return; } + ctx.strokeStyle = this.style; + if (this.ignoreScale) { ctx.save(); ctx.setTransform(1,0,0,1,0,0); } + ctx.stroke(); + if (this.ignoreScale) { ctx.restore(); } + }; + /** + * Creates a linear gradient style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. + * See {{#crossLink "Graphics/beginLinearGradientStroke"}}{{/crossLink}} for more information. + * @method linearGradient + * @param {Array} colors + * @param {Array} ratios + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} x1 + * @param {Number} y1 + * @return {Fill} Returns this Stroke object for chaining or assignment. + */ + p.linearGradient = G.Fill.prototype.linearGradient; + /** + * Creates a radial gradient style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. + * See {{#crossLink "Graphics/beginRadialGradientStroke"}}{{/crossLink}} for more information. + * @method radialGradient + * @param {Array} colors + * @param {Array} ratios + * @param {Number} x0 + * @param {Number} y0 + * @param {Number} r0 + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} r1 + * @return {Fill} Returns this Stroke object for chaining or assignment. + */ + p.radialGradient = G.Fill.prototype.radialGradient; + /** + * Creates a bitmap fill style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. + * See {{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}} for more information. + * @method bitmap + * @param {HTMLImageElement} image + * @param {String} [repetition] One of: repeat, repeat-x, repeat-y, or no-repeat. + * @return {Fill} Returns this Stroke object for chaining or assignment. + */ + p.bitmap = G.Fill.prototype.bitmap; + p.path = false; + + /** + * Graphics command object. See {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class StrokeStyle + * @constructor + * @param {Number} width + * @param {String} [caps=butt] + * @param {String} [joints=miter] + * @param {Number} [miterLimit=10] + * @param {Boolean} [ignoreScale=false] + **/ + /** + * @property width + * @type Number + */ + /** + * One of: butt, round, square + * @property caps + * @type String + */ + /** + * One of: round, bevel, miter + * @property joints + * @type String + */ + /** + * @property miterLimit + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + p = (G.StrokeStyle = function(width, caps, joints, miterLimit, ignoreScale) { + this.width = width; + this.caps = caps; + this.joints = joints; + this.miterLimit = miterLimit; + this.ignoreScale = ignoreScale; + }).prototype; + p.exec = function(ctx) { + ctx.lineWidth = (this.width == null ? "1" : this.width); + ctx.lineCap = (this.caps == null ? "butt" : (isNaN(this.caps) ? this.caps : Graphics.STROKE_CAPS_MAP[this.caps])); + ctx.lineJoin = (this.joints == null ? "miter" : (isNaN(this.joints) ? this.joints : Graphics.STROKE_JOINTS_MAP[this.joints])); + ctx.miterLimit = (this.miterLimit == null ? "10" : this.miterLimit); + ctx.ignoreScale = (this.ignoreScale == null ? false : this.ignoreScale); + }; + p.path = false; + + /** + * Graphics command object. See {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class StrokeDash + * @constructor + * @param {Array} [segments] + * @param {Number} [offset=0] + **/ + /** + * @property segments + * @type Array + */ + /** + * @property offset + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.StrokeDash = function(segments, offset) { + this.segments = segments; + this.offset = offset||0; + }).prototype.exec = function(ctx) { + if (ctx.setLineDash) { // feature detection. + ctx.setLineDash(this.segments|| G.StrokeDash.EMPTY_SEGMENTS); // instead of [] to reduce churn. + ctx.lineDashOffset = this.offset||0; + } + }; + /** + * The default value for segments (ie. no dash). + * @property EMPTY_SEGMENTS + * @static + * @final + * @readonly + * @protected + * @type {Array} + **/ + G.StrokeDash.EMPTY_SEGMENTS = []; + + /** + * Graphics command object. See {{#crossLink "Graphics/drawRoundRectComplex"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class RoundRect + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + * @param {Number} radiusTL + * @param {Number} radiusTR + * @param {Number} radiusBR + * @param {Number} radiusBL + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property w + * @type Number + */ + /** + * @property h + * @type Number + */ + /** + * @property radiusTL + * @type Number + */ + /** + * @property radiusTR + * @type Number + */ + /** + * @property radiusBR + * @type Number + */ + /** + * @property radiusBL + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.RoundRect = function(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL) { + this.x = x; this.y = y; + this.w = w; this.h = h; + this.radiusTL = radiusTL; this.radiusTR = radiusTR; + this.radiusBR = radiusBR; this.radiusBL = radiusBL; + }).prototype.exec = function(ctx) { + var max = (w max) { rTL = max; } + if (rTR < 0) { rTR *= (mTR=-1); } + if (rTR > max) { rTR = max; } + if (rBR < 0) { rBR *= (mBR=-1); } + if (rBR > max) { rBR = max; } + if (rBL < 0) { rBL *= (mBL=-1); } + if (rBL > max) { rBL = max; } + + ctx.moveTo(x+w-rTR, y); + ctx.arcTo(x+w+rTR*mTR, y-rTR*mTR, x+w, y+rTR, rTR); + ctx.lineTo(x+w, y+h-rBR); + ctx.arcTo(x+w+rBR*mBR, y+h+rBR*mBR, x+w-rBR, y+h, rBR); + ctx.lineTo(x+rBL, y+h); + ctx.arcTo(x-rBL*mBL, y+h+rBL*mBL, x, y+h-rBL, rBL); + ctx.lineTo(x, y+rTL); + ctx.arcTo(x-rTL*mTL, y-rTL*mTL, x+rTL, y, rTL); + ctx.closePath(); + }; + + /** + * Graphics command object. See {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class Circle + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} radius + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property radius + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.Circle = function(x, y, radius) { + this.x = x; this.y = y; + this.radius = radius; + }).prototype.exec = function(ctx) { ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2); }; + + /** + * Graphics command object. See {{#crossLink "Graphics/drawEllipse"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class Ellipse + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} w + * @param {Number} h + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property w + * @type Number + */ + /** + * @property h + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.Ellipse = function(x, y, w, h) { + this.x = x; this.y = y; + this.w = w; this.h = h; + }).prototype.exec = function(ctx) { + var x = this.x, y = this.y; + var w = this.w, h = this.h; + + var k = 0.5522848; + var ox = (w / 2) * k; + var oy = (h / 2) * k; + var xe = x + w; + var ye = y + h; + var xm = x + w / 2; + var ym = y + h / 2; + + ctx.moveTo(x, ym); + ctx.bezierCurveTo(x, ym-oy, xm-ox, y, xm, y); + ctx.bezierCurveTo(xm+ox, y, xe, ym-oy, xe, ym); + ctx.bezierCurveTo(xe, ym+oy, xm+ox, ye, xm, ye); + ctx.bezierCurveTo(xm-ox, ye, x, ym+oy, x, ym); + }; + + /** + * Graphics command object. See {{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class PolyStar + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} radius + * @param {Number} sides + * @param {Number} pointSize + * @param {Number} angle + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property radius + * @type Number + */ + /** + * @property sides + * @type Number + */ + /** + * @property pointSize + * @type Number + */ + /** + * @property angle + * @type Number + */ + /** + * Execute the Graphics command in the provided Canvas context. + * @method exec + * @param {CanvasRenderingContext2D} ctx The canvas rendering context + */ + (G.PolyStar = function(x, y, radius, sides, pointSize, angle) { + this.x = x; this.y = y; + this.radius = radius; + this.sides = sides; + this.pointSize = pointSize; + this.angle = angle; + }).prototype.exec = function(ctx) { + var x = this.x, y = this.y; + var radius = this.radius; + var angle = (this.angle||0)/180*Math.PI; + var sides = this.sides; + var ps = 1-(this.pointSize||0); + var a = Math.PI/sides; + + ctx.moveTo(x+Math.cos(angle)*radius, y+Math.sin(angle)*radius); + for (var i=0; iTiny API - * The Graphics class also includes a "tiny API", which is one or two-letter methods that are shortcuts for all of the - * Graphics methods. These methods are great for creating compact instructions, and is used by the Toolkit for CreateJS - * to generate readable code. All tiny methods are marked as protected, so you can view them by enabling protected - * descriptions in the docs. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
TinyMethodTinyMethod
mt{{#crossLink "Graphics/moveTo"}}{{/crossLink}} lt {{#crossLink "Graphics/lineTo"}}{{/crossLink}}
a/at{{#crossLink "Graphics/arc"}}{{/crossLink}} / {{#crossLink "Graphics/arcTo"}}{{/crossLink}} bt{{#crossLink "Graphics/bezierCurveTo"}}{{/crossLink}}
qt{{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} (also curveTo)r{{#crossLink "Graphics/rect"}}{{/crossLink}}
cp{{#crossLink "Graphics/closePath"}}{{/crossLink}} c{{#crossLink "Graphics/clear"}}{{/crossLink}}
f{{#crossLink "Graphics/beginFill"}}{{/crossLink}} lf{{#crossLink "Graphics/beginLinearGradientFill"}}{{/crossLink}}
rf{{#crossLink "Graphics/beginRadialGradientFill"}}{{/crossLink}} bf{{#crossLink "Graphics/beginBitmapFill"}}{{/crossLink}}
ef{{#crossLink "Graphics/endFill"}}{{/crossLink}} ss / sd{{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} / {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}}
s{{#crossLink "Graphics/beginStroke"}}{{/crossLink}} ls{{#crossLink "Graphics/beginLinearGradientStroke"}}{{/crossLink}}
rs{{#crossLink "Graphics/beginRadialGradientStroke"}}{{/crossLink}} bs{{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}}
es{{#crossLink "Graphics/endStroke"}}{{/crossLink}} dr{{#crossLink "Graphics/drawRect"}}{{/crossLink}}
rr{{#crossLink "Graphics/drawRoundRect"}}{{/crossLink}} rc{{#crossLink "Graphics/drawRoundRectComplex"}}{{/crossLink}}
dc{{#crossLink "Graphics/drawCircle"}}{{/crossLink}} de{{#crossLink "Graphics/drawEllipse"}}{{/crossLink}}
dp{{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} p{{#crossLink "Graphics/decodePath"}}{{/crossLink}}
- * - * Here is the above example, using the tiny API instead. - * - * myGraphics.s("red").f("blue").r(20, 20, 100, 50); - * - * @class Graphics - * @constructor - **/ - function Graphics() { - - - // public properties - /** - * Holds a reference to the last command that was created or appended. For example, you could retain a reference - * to a Fill command in order to dynamically update the color later by using: - * myFill = myGraphics.beginFill("red").command; - * // update color later: - * myFill.style = "yellow"; - * @property command - * @type Object - **/ - this.command = null; - - - // private properties - /** - * @property _stroke - * @protected - * @type {Stroke} - **/ - this._stroke = null; - - /** - * @property _strokeStyle - * @protected - * @type {StrokeStyle} - **/ - this._strokeStyle = null; - - /** - * @property _oldStrokeStyle - * @protected - * @type {StrokeStyle} - **/ - this._oldStrokeStyle = null; - - /** - * @property _strokeDash - * @protected - * @type {StrokeDash} - **/ - this._strokeDash = null; - - /** - * @property _oldStrokeDash - * @protected - * @type {StrokeDash} - **/ - this._oldStrokeDash = null; - - /** - * @property _strokeIgnoreScale - * @protected - * @type Boolean - **/ - this._strokeIgnoreScale = false; - - /** - * @property _fill - * @protected - * @type {Fill} - **/ - this._fill = null; - - /** - * @property _instructions - * @protected - * @type {Array} - **/ - this._instructions = []; - - /** - * Indicates the last instruction index that was committed. - * @property _commitIndex - * @protected - * @type {Number} - **/ - this._commitIndex = 0; - - /** - * Uncommitted instructions. - * @property _activeInstructions - * @protected - * @type {Array} - **/ - this._activeInstructions = []; - - /** - * This indicates that there have been changes to the activeInstruction list since the last updateInstructions call. - * @property _dirty - * @protected - * @type {Boolean} - * @default false - **/ - this._dirty = false; - - /** - * Index to draw from if a store operation has happened. - * @property _storeIndex - * @protected - * @type {Number} - * @default 0 - **/ - this._storeIndex = 0; - - // setup: - this.clear(); - } - var p = Graphics.prototype; - var G = Graphics; // shortcut - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// static public methods: - /** - * Returns a CSS compatible color string based on the specified RGB numeric color values in the format - * "rgba(255,255,255,1.0)", or if alpha is null then in the format "rgb(255,255,255)". For example, - * - * createjs.Graphics.getRGB(50, 100, 150, 0.5); - * // Returns "rgba(50,100,150,0.5)" - * - * It also supports passing a single hex color value as the first param, and an optional alpha value as the second - * param. For example, - * - * createjs.Graphics.getRGB(0xFF00FF, 0.2); - * // Returns "rgba(255,0,255,0.2)" - * - * @method getRGB - * @static - * @param {Number} r The red component for the color, between 0 and 0xFF (255). - * @param {Number} g The green component for the color, between 0 and 0xFF (255). - * @param {Number} b The blue component for the color, between 0 and 0xFF (255). - * @param {Number} [alpha] The alpha component for the color where 0 is fully transparent and 1 is fully opaque. - * @return {String} A CSS compatible color string based on the specified RGB numeric color values in the format - * "rgba(255,255,255,1.0)", or if alpha is null then in the format "rgb(255,255,255)". - **/ - Graphics.getRGB = function(r, g, b, alpha) { - if (r != null && b == null) { - alpha = g; - b = r&0xFF; - g = r>>8&0xFF; - r = r>>16&0xFF; - } - if (alpha == null) { - return "rgb("+r+","+g+","+b+")"; - } else { - return "rgba("+r+","+g+","+b+","+alpha+")"; - } - }; - - /** - * Returns a CSS compatible color string based on the specified HSL numeric color values in the format "hsla(360,100,100,1.0)", - * or if alpha is null then in the format "hsl(360,100,100)". - * - * createjs.Graphics.getHSL(150, 100, 70); - * // Returns "hsl(150,100,70)" - * - * @method getHSL - * @static - * @param {Number} hue The hue component for the color, between 0 and 360. - * @param {Number} saturation The saturation component for the color, between 0 and 100. - * @param {Number} lightness The lightness component for the color, between 0 and 100. - * @param {Number} [alpha] The alpha component for the color where 0 is fully transparent and 1 is fully opaque. - * @return {String} A CSS compatible color string based on the specified HSL numeric color values in the format - * "hsla(360,100,100,1.0)", or if alpha is null then in the format "hsl(360,100,100)". - **/ - Graphics.getHSL = function(hue, saturation, lightness, alpha) { - if (alpha == null) { - return "hsl("+(hue%360)+","+saturation+"%,"+lightness+"%)"; - } else { - return "hsla("+(hue%360)+","+saturation+"%,"+lightness+"%,"+alpha+")"; - } - }; - - -// static properties: - /** - * A reusable instance of {{#crossLink "Graphics/BeginPath"}}{{/crossLink}} to avoid - * unnecessary instantiation. - * @property beginCmd - * @type {Graphics.BeginPath} - * @static - **/ - // defined at the bottom of this file. - - /** - * Map of Base64 characters to values. Used by {{#crossLink "Graphics/decodePath"}}{{/crossLink}}. - * @property BASE_64 - * @static - * @final - * @readonly - * @type {Object} - **/ - Graphics.BASE_64 = {"A":0,"B":1,"C":2,"D":3,"E":4,"F":5,"G":6,"H":7,"I":8,"J":9,"K":10,"L":11,"M":12,"N":13,"O":14,"P":15,"Q":16,"R":17,"S":18,"T":19,"U":20,"V":21,"W":22,"X":23,"Y":24,"Z":25,"a":26,"b":27,"c":28,"d":29,"e":30,"f":31,"g":32,"h":33,"i":34,"j":35,"k":36,"l":37,"m":38,"n":39,"o":40,"p":41,"q":42,"r":43,"s":44,"t":45,"u":46,"v":47,"w":48,"x":49,"y":50,"z":51,"0":52,"1":53,"2":54,"3":55,"4":56,"5":57,"6":58,"7":59,"8":60,"9":61,"+":62,"/":63}; - - /** - * Maps numeric values for the caps parameter of {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} to - * corresponding string values. This is primarily for use with the tiny API. The mappings are as follows: 0 to - * "butt", 1 to "round", and 2 to "square". - * For example, to set the line caps to "square": - * - * myGraphics.ss(16, 2); - * - * @property STROKE_CAPS_MAP - * @static - * @final - * @readonly - * @type {Array} - **/ - Graphics.STROKE_CAPS_MAP = ["butt", "round", "square"]; - - /** - * Maps numeric values for the joints parameter of {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} to - * corresponding string values. This is primarily for use with the tiny API. The mappings are as follows: 0 to - * "miter", 1 to "round", and 2 to "bevel". - * For example, to set the line joints to "bevel": - * - * myGraphics.ss(16, 0, 2); - * - * @property STROKE_JOINTS_MAP - * @static - * @final - * @readonly - * @type {Array} - **/ - Graphics.STROKE_JOINTS_MAP = ["miter", "round", "bevel"]; - - /** - * @property _ctx - * @static - * @protected - * @type {CanvasRenderingContext2D} - **/ - var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); - if (canvas.getContext) { - Graphics._ctx = canvas.getContext("2d"); - canvas.width = canvas.height = 1; - } - - -// getter / setters: - /** - * Use the {{#crossLink "Graphics/instructions:property"}}{{/crossLink}} property instead. - * @method getInstructions - * @return {Array} - * @deprecated - **/ - p.getInstructions = function() { - this._updateInstructions(); - return this._instructions; - }; - - /** - * Returns the graphics instructions array. Each entry is a graphics command object (ex. Graphics.Fill, Graphics.Rect) - * Modifying the returned array directly is not recommended, and is likely to result in unexpected behaviour. - * - * This property is mainly intended for introspection of the instructions (ex. for graphics export). - * @property instructions - * @type {Array} - * @readonly - **/ - try { - Object.defineProperties(p, { - instructions: { get: p.getInstructions } - }); - } catch (e) {} - - -// public methods: - /** - * Returns true if this Graphics instance has no drawing commands. - * @method isEmpty - * @return {Boolean} Returns true if this Graphics instance has no drawing commands. - **/ - p.isEmpty = function() { - return !(this._instructions.length || this._activeInstructions.length); - }; - - /** - * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. - * Returns true if the draw was handled (useful for overriding functionality). - * - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method draw - * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - * @param {Object} data Optional data that is passed to graphics command exec methods. When called from a Shape instance, the shape passes itself as the data parameter. This can be used by custom graphic commands to insert contextual data. - **/ - p.draw = function(ctx, data) { - this._updateInstructions(); - var instr = this._instructions; - for (var i=this._storeIndex, l=instr.length; iDisplayObject.mask to draw the clipping path, for example. - * - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method drawAsPath - * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - **/ - p.drawAsPath = function(ctx) { - this._updateInstructions(); - var instr, instrs = this._instructions; - for (var i=this._storeIndex, l=instrs.length; i - * whatwg spec. - * @method lineTo - * @param {Number} x The x coordinate the drawing point should draw to. - * @param {Number} y The y coordinate the drawing point should draw to. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.lineTo = function(x, y) { - return this.append(new G.LineTo(x,y)); - }; - - /** - * Draws an arc with the specified control points and radius. For detailed information, read the - * - * whatwg spec. A tiny API method "at" also exists. - * @method arcTo - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} x2 - * @param {Number} y2 - * @param {Number} radius - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.arcTo = function(x1, y1, x2, y2, radius) { - return this.append(new G.ArcTo(x1, y1, x2, y2, radius)); - }; - - /** - * Draws an arc defined by the radius, startAngle and endAngle arguments, centered at the position (x, y). For - * example, to draw a full circle with a radius of 20 centered at (100, 100): - * - * arc(100, 100, 20, 0, Math.PI*2); - * - * For detailed information, read the - * whatwg spec. - * A tiny API method "a" also exists. - * @method arc - * @param {Number} x - * @param {Number} y - * @param {Number} radius - * @param {Number} startAngle Measured in radians. - * @param {Number} endAngle Measured in radians. - * @param {Boolean} anticlockwise - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.arc = function(x, y, radius, startAngle, endAngle, anticlockwise) { - return this.append(new G.Arc(x, y, radius, startAngle, endAngle, anticlockwise)); - }; - - /** - * Draws a quadratic curve from the current drawing point to (x, y) using the control point (cpx, cpy). For detailed - * information, read the - * whatwg spec. A tiny API method "qt" also exists. - * @method quadraticCurveTo - * @param {Number} cpx - * @param {Number} cpy - * @param {Number} x - * @param {Number} y - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.quadraticCurveTo = function(cpx, cpy, x, y) { - return this.append(new G.QuadraticCurveTo(cpx, cpy, x, y)); - }; - - /** - * Draws a bezier curve from the current drawing point to (x, y) using the control points (cp1x, cp1y) and (cp2x, - * cp2y). For detailed information, read the - * - * whatwg spec. A tiny API method "bt" also exists. - * @method bezierCurveTo - * @param {Number} cp1x - * @param {Number} cp1y - * @param {Number} cp2x - * @param {Number} cp2y - * @param {Number} x - * @param {Number} y - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { - return this.append(new G.BezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)); - }; - - /** - * Draws a rectangle at (x, y) with the specified width and height using the current fill and/or stroke. - * For detailed information, read the - * - * whatwg spec. A tiny API method "r" also exists. - * @method rect - * @param {Number} x - * @param {Number} y - * @param {Number} w Width of the rectangle - * @param {Number} h Height of the rectangle - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.rect = function(x, y, w, h) { - return this.append(new G.Rect(x, y, w, h)); - }; - - /** - * Closes the current path, effectively drawing a line from the current drawing point to the first drawing point specified - * since the fill or stroke was last set. A tiny API method "cp" also exists. - * @method closePath - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.closePath = function() { - return this._activeInstructions.length ? this.append(new G.ClosePath()) : this; - }; - - -// public methods that roughly map to Flash graphics APIs: - /** - * Clears all drawing instructions, effectively resetting this Graphics instance. Any line and fill styles will need - * to be redefined to draw shapes following a clear call. A tiny API method "c" also exists. - * @method clear - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.clear = function() { - this._instructions.length = this._activeInstructions.length = this._commitIndex = 0; - this._strokeStyle = this._oldStrokeStyle = this._stroke = this._fill = this._strokeDash = this._oldStrokeDash = null; - this._dirty = this._strokeIgnoreScale = false; - return this; - }; - - /** - * Begins a fill with the specified color. This ends the current sub-path. A tiny API method "f" also exists. - * @method beginFill - * @param {String} color A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to - * null will result in no fill. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.beginFill = function(color) { - return this._setFill(color ? new G.Fill(color) : null); - }; - - /** - * Begins a linear gradient fill defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For - * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a - * square to display it: - * - * myGraphics.beginLinearGradientFill(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120); - * - * A tiny API method "lf" also exists. - * @method beginLinearGradientFill - * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient - * drawing from red to blue. - * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw - * the first color to 10% then interpolating to the second color at 90%. - * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. - * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. - * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. - * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.beginLinearGradientFill = function(colors, ratios, x0, y0, x1, y1) { - return this._setFill(new G.Fill().linearGradient(colors, ratios, x0, y0, x1, y1)); - }; - - /** - * Begins a radial gradient fill. This ends the current sub-path. For example, the following code defines a red to - * blue radial gradient centered at (100, 100), with a radius of 50, and draws a circle to display it: - * - * myGraphics.beginRadialGradientFill(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50).drawCircle(100, 100, 50); - * - * A tiny API method "rf" also exists. - * @method beginRadialGradientFill - * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define - * a gradient drawing from red to blue. - * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, - * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. - * @param {Number} x0 Center position of the inner circle that defines the gradient. - * @param {Number} y0 Center position of the inner circle that defines the gradient. - * @param {Number} r0 Radius of the inner circle that defines the gradient. - * @param {Number} x1 Center position of the outer circle that defines the gradient. - * @param {Number} y1 Center position of the outer circle that defines the gradient. - * @param {Number} r1 Radius of the outer circle that defines the gradient. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.beginRadialGradientFill = function(colors, ratios, x0, y0, r0, x1, y1, r1) { - return this._setFill(new G.Fill().radialGradient(colors, ratios, x0, y0, r0, x1, y1, r1)); - }; - - /** - * Begins a pattern fill using the specified image. This ends the current sub-path. A tiny API method "bf" also - * exists. - * @method beginBitmapFill - * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use - * as the pattern. Must be loaded prior to creating a bitmap fill, or the fill will be empty. - * @param {String} repetition Optional. Indicates whether to repeat the image in the fill area. One of "repeat", - * "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". Note that Firefox does not support "repeat-x" or - * "repeat-y" (latest tests were in FF 20.0), and will default to "repeat". - * @param {Matrix2D} matrix Optional. Specifies a transformation matrix for the bitmap fill. This transformation - * will be applied relative to the parent transform. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.beginBitmapFill = function(image, repetition, matrix) { - return this._setFill(new G.Fill(null,matrix).bitmap(image, repetition)); - }; - - /** - * Ends the current sub-path, and begins a new one with no fill. Functionally identical to beginFill(null). - * A tiny API method "ef" also exists. - * @method endFill - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.endFill = function() { - return this.beginFill(); - }; - - /** - * Sets the stroke style. Like all drawing methods, this can be chained, so you can define - * the stroke style and color in a single line of code like so: - * - * myGraphics.setStrokeStyle(8,"round").beginStroke("#F00"); - * - * A tiny API method "ss" also exists. - * @method setStrokeStyle - * @param {Number} thickness The width of the stroke. - * @param {String | Number} [caps=0] Indicates the type of caps to use at the end of lines. One of butt, - * round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with - * the tiny API. - * @param {String | Number} [joints=0] Specifies the type of joints that should be used where two lines meet. - * One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel) - * for use with the tiny API. - * @param {Number} [miterLimit=10] If joints is set to "miter", then you can specify a miter limit ratio which - * controls at what point a mitered joint will be clipped. - * @param {Boolean} [ignoreScale=false] If true, the stroke will be drawn at the specified thickness regardless - * of active transformations. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.setStrokeStyle = function(thickness, caps, joints, miterLimit, ignoreScale) { - this._updateInstructions(true); - this._strokeStyle = this.command = new G.StrokeStyle(thickness, caps, joints, miterLimit, ignoreScale); - - // ignoreScale lives on Stroke, not StrokeStyle, so we do a little trickery: - if (this._stroke) { this._stroke.ignoreScale = ignoreScale; } - this._strokeIgnoreScale = ignoreScale; - return this; - }; - - /** - * Sets or clears the stroke dash pattern. - * - * myGraphics.setStrokeDash([20, 10], 0); - * - * A tiny API method `sd` also exists. - * @method setStrokeDash - * @param {Array} [segments] An array specifying the dash pattern, alternating between line and gap. - * For example, `[20,10]` would create a pattern of 20 pixel lines with 10 pixel gaps between them. - * Passing null or an empty array will clear the existing stroke dash. - * @param {Number} [offset=0] The offset of the dash pattern. For example, you could increment this value to create a "marching ants" effect. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.setStrokeDash = function(segments, offset) { - this._updateInstructions(true); - this._strokeDash = this.command = new G.StrokeDash(segments, offset); - return this; - }; - - /** - * Begins a stroke with the specified color. This ends the current sub-path. A tiny API method "s" also exists. - * @method beginStroke - * @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to - * null will result in no stroke. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.beginStroke = function(color) { - return this._setStroke(color ? new G.Stroke(color) : null); - }; - - /** - * Begins a linear gradient stroke defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For - * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a - * square to display it: - * - * myGraphics.setStrokeStyle(10). - * beginLinearGradientStroke(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120); - * - * A tiny API method "ls" also exists. - * @method beginLinearGradientStroke - * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define - * a gradient drawing from red to blue. - * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, - * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. - * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. - * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. - * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. - * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.beginLinearGradientStroke = function(colors, ratios, x0, y0, x1, y1) { - return this._setStroke(new G.Stroke().linearGradient(colors, ratios, x0, y0, x1, y1)); - }; - - /** - * Begins a radial gradient stroke. This ends the current sub-path. For example, the following code defines a red to - * blue radial gradient centered at (100, 100), with a radius of 50, and draws a rectangle to display it: - * - * myGraphics.setStrokeStyle(10) - * .beginRadialGradientStroke(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50) - * .drawRect(50, 90, 150, 110); - * - * A tiny API method "rs" also exists. - * @method beginRadialGradientStroke - * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define - * a gradient drawing from red to blue. - * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, - * 0.9] would draw the first color to 10% then interpolating to the second color at 90%, then draw the second color - * to 100%. - * @param {Number} x0 Center position of the inner circle that defines the gradient. - * @param {Number} y0 Center position of the inner circle that defines the gradient. - * @param {Number} r0 Radius of the inner circle that defines the gradient. - * @param {Number} x1 Center position of the outer circle that defines the gradient. - * @param {Number} y1 Center position of the outer circle that defines the gradient. - * @param {Number} r1 Radius of the outer circle that defines the gradient. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.beginRadialGradientStroke = function(colors, ratios, x0, y0, r0, x1, y1, r1) { - return this._setStroke(new G.Stroke().radialGradient(colors, ratios, x0, y0, r0, x1, y1, r1)); - }; - - /** - * Begins a pattern fill using the specified image. This ends the current sub-path. Note that unlike bitmap fills, - * strokes do not currently support a matrix parameter due to limitations in the canvas API. A tiny API method "bs" - * also exists. - * @method beginBitmapStroke - * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use - * as the pattern. Must be loaded prior to creating a bitmap fill, or the fill will be empty. - * @param {String} [repetition=repeat] Optional. Indicates whether to repeat the image in the fill area. One of - * "repeat", "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.beginBitmapStroke = function(image, repetition) { - // NOTE: matrix is not supported for stroke because transforms on strokes also affect the drawn stroke width. - return this._setStroke(new G.Stroke().bitmap(image, repetition)); - }; - - /** - * Ends the current sub-path, and begins a new one with no stroke. Functionally identical to beginStroke(null). - * A tiny API method "es" also exists. - * @method endStroke - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.endStroke = function() { - return this.beginStroke(); - }; - - /** - * Maps the familiar ActionScript curveTo() method to the functionally similar {{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} - * method. - * @method quadraticCurveTo - * @param {Number} cpx - * @param {Number} cpy - * @param {Number} x - * @param {Number} y - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.curveTo = p.quadraticCurveTo; - - /** - * - * Maps the familiar ActionScript drawRect() method to the functionally similar {{#crossLink "Graphics/rect"}}{{/crossLink}} - * method. - * @method drawRect - * @param {Number} x - * @param {Number} y - * @param {Number} w Width of the rectangle - * @param {Number} h Height of the rectangle - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.drawRect = p.rect; - - /** - * Draws a rounded rectangle with all corners with the specified radius. - * @method drawRoundRect - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - * @param {Number} radius Corner radius. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.drawRoundRect = function(x, y, w, h, radius) { - return this.drawRoundRectComplex(x, y, w, h, radius, radius, radius, radius); - }; - - /** - * Draws a rounded rectangle with different corner radii. Supports positive and negative corner radii. A tiny API - * method "rc" also exists. - * @method drawRoundRectComplex - * @param {Number} x The horizontal coordinate to draw the round rect. - * @param {Number} y The vertical coordinate to draw the round rect. - * @param {Number} w The width of the round rect. - * @param {Number} h The height of the round rect. - * @param {Number} radiusTL Top left corner radius. - * @param {Number} radiusTR Top right corner radius. - * @param {Number} radiusBR Bottom right corner radius. - * @param {Number} radiusBL Bottom left corner radius. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.drawRoundRectComplex = function(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL) { - return this.append(new G.RoundRect(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL)); - }; - - /** - * Draws a circle with the specified radius at (x, y). - * - * var g = new createjs.Graphics(); - * g.setStrokeStyle(1); - * g.beginStroke(createjs.Graphics.getRGB(0,0,0)); - * g.beginFill(createjs.Graphics.getRGB(255,0,0)); - * g.drawCircle(0,0,3); - * - * var s = new createjs.Shape(g); - * s.x = 100; - * s.y = 100; - * - * stage.addChild(s); - * stage.update(); - * - * A tiny API method "dc" also exists. - * @method drawCircle - * @param {Number} x x coordinate center point of circle. - * @param {Number} y y coordinate center point of circle. - * @param {Number} radius Radius of circle. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.drawCircle = function(x, y, radius) { - return this.append(new G.Circle(x, y, radius)); - }; - - /** - * Draws an ellipse (oval) with a specified width (w) and height (h). Similar to {{#crossLink "Graphics/drawCircle"}}{{/crossLink}}, - * except the width and height can be different. A tiny API method "de" also exists. - * @method drawEllipse - * @param {Number} x The left coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} - * which draws from center. - * @param {Number} y The top coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} - * which draws from the center. - * @param {Number} w The height (horizontal diameter) of the ellipse. The horizontal radius will be half of this - * number. - * @param {Number} h The width (vertical diameter) of the ellipse. The vertical radius will be half of this number. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.drawEllipse = function(x, y, w, h) { - return this.append(new G.Ellipse(x, y, w, h)); - }; - - /** - * Draws a star if pointSize is greater than 0, or a regular polygon if pointSize is 0 with the specified number of - * points. For example, the following code will draw a familiar 5 pointed star shape centered at 100, 100 and with a - * radius of 50: - * - * myGraphics.beginFill("#FF0").drawPolyStar(100, 100, 50, 5, 0.6, -90); - * // Note: -90 makes the first point vertical - * - * A tiny API method "dp" also exists. - * - * @method drawPolyStar - * @param {Number} x Position of the center of the shape. - * @param {Number} y Position of the center of the shape. - * @param {Number} radius The outer radius of the shape. - * @param {Number} sides The number of points on the star or sides on the polygon. - * @param {Number} pointSize The depth or "pointy-ness" of the star points. A pointSize of 0 will draw a regular - * polygon (no points), a pointSize of 1 will draw nothing because the points are infinitely pointy. - * @param {Number} angle The angle of the first point / corner. For example a value of 0 will draw the first point - * directly to the right of the center. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.drawPolyStar = function(x, y, radius, sides, pointSize, angle) { - return this.append(new G.PolyStar(x, y, radius, sides, pointSize, angle)); - }; - - // TODO: deprecated. - /** - * Removed in favour of using custom command objects with {{#crossLink "Graphics/append"}}{{/crossLink}}. - * @method inject - * @deprecated - **/ - - /** - * Appends a graphics command object to the graphics queue. Command objects expose an "exec" method - * that accepts two parameters: the Context2D to operate on, and an arbitrary data object passed into - * {{#crossLink "Graphics/draw"}}{{/crossLink}}. The latter will usually be the Shape instance that called draw. - * - * This method is used internally by Graphics methods, such as drawCircle, but can also be used directly to insert - * built-in or custom graphics commands. For example: - * - * // attach data to our shape, so we can access it during the draw: - * myShape.color = "red"; - * - * // append a Circle command object: - * myShape.graphics.append(new Graphics.Circle(50, 50, 30)); - * - * // append a custom command object with an exec method that sets the fill style - * // based on the shape's data, and then fills the circle. - * myShape.graphics.append({exec:function(ctx, shape) { - * ctx.fillStyle = shape.color; - * ctx.fill(); - * }}); - * - * @method append - * @param {Object} command A graphics command object exposing an "exec" method. - * @param {boolean} clean The clean param is primarily for internal use. A value of true indicates that a command does not generate a path that should be stroked or filled. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.append = function(command, clean) { - this._activeInstructions.push(command); - this.command = command; - if (!clean) { this._dirty = true; } - return this; - }; - - /** - * Decodes a compact encoded path string into a series of draw instructions. - * This format is not intended to be human readable, and is meant for use by authoring tools. - * The format uses a base64 character set, with each character representing 6 bits, to define a series of draw - * commands. - * - * Each command is comprised of a single "header" character followed by a variable number of alternating x and y - * position values. Reading the header bits from left to right (most to least significant): bits 1 to 3 specify the - * type of operation (0-moveTo, 1-lineTo, 2-quadraticCurveTo, 3-bezierCurveTo, 4-closePath, 5-7 unused). Bit 4 - * indicates whether position values use 12 bits (2 characters) or 18 bits (3 characters), with a one indicating the - * latter. Bits 5 and 6 are currently unused. - * - * Following the header is a series of 0 (closePath), 2 (moveTo, lineTo), 4 (quadraticCurveTo), or 6 (bezierCurveTo) - * parameters. These parameters are alternating x/y positions represented by 2 or 3 characters (as indicated by the - * 4th bit in the command char). These characters consist of a 1 bit sign (1 is negative, 0 is positive), followed - * by an 11 (2 char) or 17 (3 char) bit integer value. All position values are in tenths of a pixel. Except in the - * case of move operations which are absolute, this value is a delta from the previous x or y position (as - * appropriate). - * - * For example, the string "A3cAAMAu4AAA" represents a line starting at -150,0 and ending at 150,0. - *
A - bits 000000. First 3 bits (000) indicate a moveTo operation. 4th bit (0) indicates 2 chars per - * parameter. - *
n0 - 110111011100. Absolute x position of -150.0px. First bit indicates a negative value, remaining bits - * indicate 1500 tenths of a pixel. - *
AA - 000000000000. Absolute y position of 0. - *
I - 001100. First 3 bits (001) indicate a lineTo operation. 4th bit (1) indicates 3 chars per parameter. - *
Au4 - 000000101110111000. An x delta of 300.0px, which is added to the previous x value of -150.0px to - * provide an absolute position of +150.0px. - *
AAA - 000000000000000000. A y delta value of 0. - * - * A tiny API method "p" also exists. - * @method decodePath - * @param {String} str The path string to decode. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.decodePath = function(str) { - var instructions = [this.moveTo, this.lineTo, this.quadraticCurveTo, this.bezierCurveTo, this.closePath]; - var paramCount = [2, 2, 4, 6, 0]; - var i=0, l=str.length; - var params = []; - var x=0, y=0; - var base64 = Graphics.BASE_64; - - while (i>3; // highest order bits 1-3 code for operation. - var f = instructions[fi]; - // check that we have a valid instruction & that the unused bits are empty: - if (!f || (n&3)) { throw("bad path data (@"+i+"): "+c); } - var pl = paramCount[fi]; - if (!fi) { x=y=0; } // move operations reset the position. - params.length = 0; - i++; - var charCount = (n>>2&1)+2; // 4th header bit indicates number size for this operation. - for (var p=0; p>5) ? -1 : 1; - num = ((num&31)<<6)|(base64[str.charAt(i+1)]); - if (charCount == 3) { num = (num<<6)|(base64[str.charAt(i+2)]); } - num = sign*num/10; - if (p%2) { x = (num += x); } - else { y = (num += y); } - params[p] = num; - i += charCount; - } - f.apply(this,params); - } - return this; - }; - - /** - * Stores all graphics commands so they won't be executed in future draws. Calling store() a second time adds to - * the existing store. This also affects `drawAsPath()`. - * - * This is useful in cases where you are creating vector graphics in an iterative manner (ex. generative art), so - * that only new graphics need to be drawn (which can provide huge performance benefits), but you wish to retain all - * of the vector instructions for later use (ex. scaling, modifying, or exporting). - * - * Note that calling store() will force the active path (if any) to be ended in a manner similar to changing - * the fill or stroke. - * - * For example, consider a application where the user draws lines with the mouse. As each line segment (or collection of - * segments) are added to a Shape, it can be rasterized using {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}}, - * and then stored, so that it can be redrawn at a different scale when the application is resized, or exported to SVG. - * - * // set up cache: - * myShape.cache(0,0,500,500,scale); - * - * // when the user drags, draw a new line: - * myShape.graphics.moveTo(oldX,oldY).lineTo(newX,newY); - * // then draw it into the existing cache: - * myShape.updateCache("source-over"); - * // store the new line, so it isn't redrawn next time: - * myShape.store(); - * - * // then, when the window resizes, we can re-render at a different scale: - * // first, unstore all our lines: - * myShape.unstore(); - * // then cache using the new scale: - * myShape.cache(0,0,500,500,newScale); - * // finally, store the existing commands again: - * myShape.store(); - * - * @method store - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.store = function() { - this._updateInstructions(true); - this._storeIndex = this._instructions.length; - return this; - }; - - /** - * Unstores any graphics commands that were previously stored using {{#crossLink "Graphics/store"}}{{/crossLink}} - * so that they will be executed in subsequent draw calls. - * - * @method unstore - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.unstore = function() { - this._storeIndex = 0; - return this; - }; - - /** - * Returns a clone of this Graphics instance. Note that the individual command objects are not cloned. - * @method clone - * @return {Graphics} A clone of the current Graphics instance. - **/ - p.clone = function() { - var o = new Graphics(); - o.command = this.command; - o._stroke = this._stroke; - o._strokeStyle = this._strokeStyle; - o._strokeDash = this._strokeDash; - o._strokeIgnoreScale = this._strokeIgnoreScale; - o._fill = this._fill; - o._instructions = this._instructions.slice(); - o._commitIndex = this._commitIndex; - o._activeInstructions = this._activeInstructions.slice(); - o._dirty = this._dirty; - o._storeIndex = this._storeIndex; - return o; - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Graphics]"; - }; - - -// tiny API: - /** - * Shortcut to moveTo. - * @method mt - * @param {Number} x The x coordinate the drawing point should move to. - * @param {Number} y The y coordinate the drawing point should move to. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls). - * @chainable - * @protected - **/ - p.mt = p.moveTo; - - /** - * Shortcut to lineTo. - * @method lt - * @param {Number} x The x coordinate the drawing point should draw to. - * @param {Number} y The y coordinate the drawing point should draw to. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.lt = p.lineTo; - - /** - * Shortcut to arcTo. - * @method at - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} x2 - * @param {Number} y2 - * @param {Number} radius - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.at = p.arcTo; - - /** - * Shortcut to bezierCurveTo. - * @method bt - * @param {Number} cp1x - * @param {Number} cp1y - * @param {Number} cp2x - * @param {Number} cp2y - * @param {Number} x - * @param {Number} y - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.bt = p.bezierCurveTo; - - /** - * Shortcut to quadraticCurveTo / curveTo. - * @method qt - * @param {Number} cpx - * @param {Number} cpy - * @param {Number} x - * @param {Number} y - * @protected - * @chainable - **/ - p.qt = p.quadraticCurveTo; - - /** - * Shortcut to arc. - * @method a - * @param {Number} x - * @param {Number} y - * @param {Number} radius - * @param {Number} startAngle Measured in radians. - * @param {Number} endAngle Measured in radians. - * @param {Boolean} anticlockwise - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @protected - * @chainable - **/ - p.a = p.arc; - - /** - * Shortcut to rect. - * @method r - * @param {Number} x - * @param {Number} y - * @param {Number} w Width of the rectangle - * @param {Number} h Height of the rectangle - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.r = p.rect; - - /** - * Shortcut to closePath. - * @method cp - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.cp = p.closePath; - - /** - * Shortcut to clear. - * @method c - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.c = p.clear; - - /** - * Shortcut to beginFill. - * @method f - * @param {String} color A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to - * null will result in no fill. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.f = p.beginFill; - - /** - * Shortcut to beginLinearGradientFill. - * @method lf - * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient - * drawing from red to blue. - * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw - * the first color to 10% then interpolating to the second color at 90%. - * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. - * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. - * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. - * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.lf = p.beginLinearGradientFill; - - /** - * Shortcut to beginRadialGradientFill. - * @method rf - * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define - * a gradient drawing from red to blue. - * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, - * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. - * @param {Number} x0 Center position of the inner circle that defines the gradient. - * @param {Number} y0 Center position of the inner circle that defines the gradient. - * @param {Number} r0 Radius of the inner circle that defines the gradient. - * @param {Number} x1 Center position of the outer circle that defines the gradient. - * @param {Number} y1 Center position of the outer circle that defines the gradient. - * @param {Number} r1 Radius of the outer circle that defines the gradient. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.rf = p.beginRadialGradientFill; - - /** - * Shortcut to beginBitmapFill. - * @method bf - * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use - * as the pattern. - * @param {String} repetition Optional. Indicates whether to repeat the image in the fill area. One of "repeat", - * "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". Note that Firefox does not support "repeat-x" or - * "repeat-y" (latest tests were in FF 20.0), and will default to "repeat". - * @param {Matrix2D} matrix Optional. Specifies a transformation matrix for the bitmap fill. This transformation - * will be applied relative to the parent transform. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.bf = p.beginBitmapFill; - - /** - * Shortcut to endFill. - * @method ef - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.ef = p.endFill; - - /** - * Shortcut to setStrokeStyle. - * @method ss - * @param {Number} thickness The width of the stroke. - * @param {String | Number} [caps=0] Indicates the type of caps to use at the end of lines. One of butt, - * round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with - * the tiny API. - * @param {String | Number} [joints=0] Specifies the type of joints that should be used where two lines meet. - * One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel) - * for use with the tiny API. - * @param {Number} [miterLimit=10] If joints is set to "miter", then you can specify a miter limit ratio which - * controls at what point a mitered joint will be clipped. - * @param {Boolean} [ignoreScale=false] If true, the stroke will be drawn at the specified thickness regardless - * of active transformations. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.ss = p.setStrokeStyle; - - /** - * Shortcut to setStrokeDash. - * @method sd - * @param {Array} [segments] An array specifying the dash pattern, alternating between line and gap. - * For example, [20,10] would create a pattern of 20 pixel lines with 10 pixel gaps between them. - * Passing null or an empty array will clear any existing dash. - * @param {Number} [offset=0] The offset of the dash pattern. For example, you could increment this value to create a "marching ants" effect. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.sd = p.setStrokeDash; - - /** - * Shortcut to beginStroke. - * @method s - * @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to - * null will result in no stroke. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.s = p.beginStroke; - - /** - * Shortcut to beginLinearGradientStroke. - * @method ls - * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define - * a gradient drawing from red to blue. - * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, - * 0.9] would draw the first color to 10% then interpolating to the second color at 90%. - * @param {Number} x0 The position of the first point defining the line that defines the gradient direction and size. - * @param {Number} y0 The position of the first point defining the line that defines the gradient direction and size. - * @param {Number} x1 The position of the second point defining the line that defines the gradient direction and size. - * @param {Number} y1 The position of the second point defining the line that defines the gradient direction and size. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.ls = p.beginLinearGradientStroke; - - /** - * Shortcut to beginRadialGradientStroke. - * @method rs - * @param {Array} colors An array of CSS compatible color values. For example, ["#F00","#00F"] would define - * a gradient drawing from red to blue. - * @param {Array} ratios An array of gradient positions which correspond to the colors. For example, [0.1, - * 0.9] would draw the first color to 10% then interpolating to the second color at 90%, then draw the second color - * to 100%. - * @param {Number} x0 Center position of the inner circle that defines the gradient. - * @param {Number} y0 Center position of the inner circle that defines the gradient. - * @param {Number} r0 Radius of the inner circle that defines the gradient. - * @param {Number} x1 Center position of the outer circle that defines the gradient. - * @param {Number} y1 Center position of the outer circle that defines the gradient. - * @param {Number} r1 Radius of the outer circle that defines the gradient. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.rs = p.beginRadialGradientStroke; - - /** - * Shortcut to beginBitmapStroke. - * @method bs - * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} image The Image, Canvas, or Video object to use - * as the pattern. - * @param {String} [repetition=repeat] Optional. Indicates whether to repeat the image in the fill area. One of - * "repeat", "repeat-x", "repeat-y", or "no-repeat". Defaults to "repeat". - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.bs = p.beginBitmapStroke; - - /** - * Shortcut to endStroke. - * @method es - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.es = p.endStroke; - - /** - * Shortcut to drawRect. - * @method dr - * @param {Number} x - * @param {Number} y - * @param {Number} w Width of the rectangle - * @param {Number} h Height of the rectangle - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.dr = p.drawRect; - - /** - * Shortcut to drawRoundRect. - * @method rr - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - * @param {Number} radius Corner radius. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.rr = p.drawRoundRect; - - /** - * Shortcut to drawRoundRectComplex. - * @method rc - * @param {Number} x The horizontal coordinate to draw the round rect. - * @param {Number} y The vertical coordinate to draw the round rect. - * @param {Number} w The width of the round rect. - * @param {Number} h The height of the round rect. - * @param {Number} radiusTL Top left corner radius. - * @param {Number} radiusTR Top right corner radius. - * @param {Number} radiusBR Bottom right corner radius. - * @param {Number} radiusBL Bottom left corner radius. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.rc = p.drawRoundRectComplex; - - /** - * Shortcut to drawCircle. - * @method dc - * @param {Number} x x coordinate center point of circle. - * @param {Number} y y coordinate center point of circle. - * @param {Number} radius Radius of circle. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.dc = p.drawCircle; - - /** - * Shortcut to drawEllipse. - * @method de - * @param {Number} x The left coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} - * which draws from center. - * @param {Number} y The top coordinate point of the ellipse. Note that this is different from {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} - * which draws from the center. - * @param {Number} w The height (horizontal diameter) of the ellipse. The horizontal radius will be half of this - * number. - * @param {Number} h The width (vertical diameter) of the ellipse. The vertical radius will be half of this number. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.de = p.drawEllipse; - - /** - * Shortcut to drawPolyStar. - * @method dp - * @param {Number} x Position of the center of the shape. - * @param {Number} y Position of the center of the shape. - * @param {Number} radius The outer radius of the shape. - * @param {Number} sides The number of points on the star or sides on the polygon. - * @param {Number} pointSize The depth or "pointy-ness" of the star points. A pointSize of 0 will draw a regular - * polygon (no points), a pointSize of 1 will draw nothing because the points are infinitely pointy. - * @param {Number} angle The angle of the first point / corner. For example a value of 0 will draw the first point - * directly to the right of the center. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.dp = p.drawPolyStar; - - /** - * Shortcut to decodePath. - * @method p - * @param {String} str The path string to decode. - * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) - * @chainable - * @protected - **/ - p.p = p.decodePath; - - -// private methods: - /** - * @method _updateInstructions - * @param commit - * @protected - **/ - p._updateInstructions = function(commit) { - var instr = this._instructions, active = this._activeInstructions, commitIndex = this._commitIndex; - - if (this._dirty && active.length) { - instr.length = commitIndex; // remove old, uncommitted commands - instr.push(Graphics.beginCmd); - - var l = active.length, ll = instr.length; - instr.length = ll+l; - for (var i=0; i= 2) { - var o = this.style = Graphics._ctx.createPattern(image, repetition || ""); - o.props = {image: image, repetition: repetition, type: "bitmap"}; - } - return this; - }; - p.path = false; - - /** - * Graphics command object. See {{#crossLink "Graphics/beginStroke"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. - * @class Stroke - * @constructor - * @param {Object} style A valid Context2D fillStyle. - * @param {Boolean} ignoreScale - **/ - /** - * A valid Context2D strokeStyle. - * @property style - * @type Object - */ - /** - * @property ignoreScale - * @type Boolean - */ - /** - * @method exec - * @param {CanvasRenderingContext2D} ctx - */ - p = (G.Stroke = function(style, ignoreScale) { - this.style = style; - this.ignoreScale = ignoreScale; - }).prototype; - p.exec = function(ctx) { - if (!this.style) { return; } - ctx.strokeStyle = this.style; - if (this.ignoreScale) { ctx.save(); ctx.setTransform(1,0,0,1,0,0); } - ctx.stroke(); - if (this.ignoreScale) { ctx.restore(); } - }; - /** - * Creates a linear gradient style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. - * See {{#crossLink "Graphics/beginLinearGradientStroke"}}{{/crossLink}} for more information. - * @method linearGradient - * @param {Array} colors - * @param {Array} ratios - * @param {Number} x0 - * @param {Number} y0 - * @param {Number} x1 - * @param {Number} y1 - * @return {Fill} Returns this Stroke object for chaining or assignment. - */ - p.linearGradient = G.Fill.prototype.linearGradient; - /** - * Creates a radial gradient style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. - * See {{#crossLink "Graphics/beginRadialGradientStroke"}}{{/crossLink}} for more information. - * @method radialGradient - * @param {Array} colors - * @param {Array} ratios - * @param {Number} x0 - * @param {Number} y0 - * @param {Number} r0 - * @param {Number} x1 - * @param {Number} y1 - * @param {Number} r1 - * @return {Fill} Returns this Stroke object for chaining or assignment. - */ - p.radialGradient = G.Fill.prototype.radialGradient; - /** - * Creates a bitmap fill style and assigns it to {{#crossLink "Stroke/style:property"}}{{/crossLink}}. - * See {{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}} for more information. - * @method bitmap - * @param {HTMLImageElement} image - * @param {String} [repetition] One of: repeat, repeat-x, repeat-y, or no-repeat. - * @return {Fill} Returns this Stroke object for chaining or assignment. - */ - p.bitmap = G.Fill.prototype.bitmap; - p.path = false; - - /** - * Graphics command object. See {{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. - * @class StrokeStyle - * @constructor - * @param {Number} width - * @param {String} [caps] - * @param {String} [joints] - * @param {Number} [miterLimit] - **/ - /** - * @property width - * @type Number - */ - /** - * One of: butt, round, square - * @property caps - * @type String - */ - /** - * One of: round, bevel, miter - * @property joints - * @type String - */ - /** - * @property miterLimit - * @type Number - */ - /** - * @method exec - * @param {CanvasRenderingContext2D} ctx - */ - p = (G.StrokeStyle = function(width, caps, joints, miterLimit) { - this.width = width; - this.caps = caps; - this.joints = joints; - this.miterLimit = miterLimit; - }).prototype; - p.exec = function(ctx) { - ctx.lineWidth = (this.width == null ? "1" : this.width); - ctx.lineCap = (this.caps == null ? "butt" : (isNaN(this.caps) ? this.caps : Graphics.STROKE_CAPS_MAP[this.caps])); - ctx.lineJoin = (this.joints == null ? "miter" : (isNaN(this.joints) ? this.joints : Graphics.STROKE_JOINTS_MAP[this.joints])); - ctx.miterLimit = (this.miterLimit == null ? "10" : this.miterLimit); - }; - p.path = false; - - /** - * Graphics command object. See {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. - * @class StrokeDash - * @constructor - * @param {Array} [segments] - * @param {Number} [offset=0] - **/ - /** - * @property segments - * @type Array - */ - /** - * @property offset - * @type Number - */ - /** - * @method exec - * @param {CanvasRenderingContext2D} ctx - */ - (G.StrokeDash = function(segments, offset) { - this.segments = segments; - this.offset = offset||0; - }).prototype.exec = function(ctx) { - if (ctx.setLineDash) { // feature detection. - ctx.setLineDash(this.segments|| G.StrokeDash.EMPTY_SEGMENTS); // instead of [] to reduce churn. - ctx.lineDashOffset = this.offset||0; - } - }; - /** - * The default value for segments (ie. no dash). - * @property EMPTY_SEGMENTS - * @static - * @final - * @readonly - * @protected - * @type {Array} - **/ - G.StrokeDash.EMPTY_SEGMENTS = []; - - /** - * Graphics command object. See {{#crossLink "Graphics/drawRoundRectComplex"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. - * @class RoundRect - * @constructor - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - * @param {Number} radiusTL - * @param {Number} radiusTR - * @param {Number} radiusBR - * @param {Number} radiusBL - **/ - /** - * @property x - * @type Number - */ - /** - * @property y - * @type Number - */ - /** - * @property w - * @type Number - */ - /** - * @property h - * @type Number - */ - /** - * @property radiusTL - * @type Number - */ - /** - * @property radiusTR - * @type Number - */ - /** - * @property radiusBR - * @type Number - */ - /** - * @property radiusBL - * @type Number - */ - /** - * @method exec - * @param {CanvasRenderingContext2D} ctx - */ - (G.RoundRect = function(x, y, w, h, radiusTL, radiusTR, radiusBR, radiusBL) { - this.x = x; this.y = y; - this.w = w; this.h = h; - this.radiusTL = radiusTL; this.radiusTR = radiusTR; - this.radiusBR = radiusBR; this.radiusBL = radiusBL; - }).prototype.exec = function(ctx) { - var max = (w max) { rTL = max; } - if (rTR < 0) { rTR *= (mTR=-1); } - if (rTR > max) { rTR = max; } - if (rBR < 0) { rBR *= (mBR=-1); } - if (rBR > max) { rBR = max; } - if (rBL < 0) { rBL *= (mBL=-1); } - if (rBL > max) { rBL = max; } - - ctx.moveTo(x+w-rTR, y); - ctx.arcTo(x+w+rTR*mTR, y-rTR*mTR, x+w, y+rTR, rTR); - ctx.lineTo(x+w, y+h-rBR); - ctx.arcTo(x+w+rBR*mBR, y+h+rBR*mBR, x+w-rBR, y+h, rBR); - ctx.lineTo(x+rBL, y+h); - ctx.arcTo(x-rBL*mBL, y+h+rBL*mBL, x, y+h-rBL, rBL); - ctx.lineTo(x, y+rTL); - ctx.arcTo(x-rTL*mTL, y-rTL*mTL, x+rTL, y, rTL); - ctx.closePath(); - }; - - /** - * Graphics command object. See {{#crossLink "Graphics/drawCircle"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. - * @class Circle - * @constructor - * @param {Number} x - * @param {Number} y - * @param {Number} radius - **/ - /** - * @property x - * @type Number - */ - /** - * @property y - * @type Number - */ - /** - * @property radius - * @type Number - */ - /** - * @method exec - * @param {CanvasRenderingContext2D} ctx - */ - (G.Circle = function(x, y, radius) { - this.x = x; this.y = y; - this.radius = radius; - }).prototype.exec = function(ctx) { ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2); }; - - /** - * Graphics command object. See {{#crossLink "Graphics/drawEllipse"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. - * @class Ellipse - * @constructor - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - **/ - /** - * @property x - * @type Number - */ - /** - * @property y - * @type Number - */ - /** - * @property w - * @type Number - */ - /** - * @property h - * @type Number - */ - /** - * @method exec - * @param {CanvasRenderingContext2D} ctx - */ - (G.Ellipse = function(x, y, w, h) { - this.x = x; this.y = y; - this.w = w; this.h = h; - }).prototype.exec = function(ctx) { - var x = this.x, y = this.y; - var w = this.w, h = this.h; - - var k = 0.5522848; - var ox = (w / 2) * k; - var oy = (h / 2) * k; - var xe = x + w; - var ye = y + h; - var xm = x + w / 2; - var ym = y + h / 2; - - ctx.moveTo(x, ym); - ctx.bezierCurveTo(x, ym-oy, xm-ox, y, xm, y); - ctx.bezierCurveTo(xm+ox, y, xe, ym-oy, xe, ym); - ctx.bezierCurveTo(xe, ym+oy, xm+ox, ye, xm, ye); - ctx.bezierCurveTo(xm-ox, ye, x, ym+oy, x, ym); - }; - - /** - * Graphics command object. See {{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. - * @class PolyStar - * @constructor - * @param {Number} x - * @param {Number} y - * @param {Number} radius - * @param {Number} sides - * @param {Number} pointSize - * @param {Number} angle - **/ - /** - * @property x - * @type Number - */ - /** - * @property y - * @type Number - */ - /** - * @property radius - * @type Number - */ - /** - * @property sides - * @type Number - */ - /** - * @property pointSize - * @type Number - */ - /** - * @property angle - * @type Number - */ - /** - * @method exec - * @param {CanvasRenderingContext2D} ctx - */ - (G.PolyStar = function(x, y, radius, sides, pointSize, angle) { - this.x = x; this.y = y; - this.radius = radius; - this.sides = sides; - this.pointSize = pointSize; - this.angle = angle; - }).prototype.exec = function(ctx) { - var x = this.x, y = this.y; - var radius = this.radius; - var angle = (this.angle||0)/180*Math.PI; - var sides = this.sides; - var ps = 1-(this.pointSize||0); - var a = Math.PI/sides; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * DisplayObject is an abstract class that should not be constructed directly. Instead construct subclasses such as + * {{#crossLink "Container"}}{{/crossLink}}, {{#crossLink "Bitmap"}}{{/crossLink}}, and {{#crossLink "Shape"}}{{/crossLink}}. + * DisplayObject is the base class for all display classes in the EaselJS library. It defines the core properties and + * methods that are shared between all display objects, such as transformation properties (x, y, scaleX, scaleY, etc), + * caching, and mouse handlers. + * @class DisplayObject + * @extends EventDispatcher + * @constructor + **/ + function DisplayObject() { + this.EventDispatcher_constructor(); + + + // public properties: + /** + * The alpha (transparency) for this display object. 0 is fully transparent, 1 is fully opaque. + * @property alpha + * @type {Number} + * @default 1 + **/ + this.alpha = 1; + + /** + * If a cache is active, this returns the canvas that holds the cached version of this display object. See {{#crossLink "cache"}}{{/crossLink}} + * for more information. + * @property cacheCanvas + * @type {HTMLCanvasElement | Object} + * @default null + * @readonly + **/ + this.cacheCanvas = null; + + /** + * Returns an ID number that uniquely identifies the current cache for this display object. This can be used to + * determine if the cache has changed since a previous check. + * @property cacheID + * @type {Number} + * @default 0 + */ + this.cacheID = 0; + + /** + * Unique ID for this display object. Makes display objects easier for some uses. + * @property id + * @type {Number} + * @default -1 + **/ + this.id = createjs.UID.get(); + + /** + * Indicates whether to include this object when running mouse interactions. Setting this to `false` for children + * of a {{#crossLink "Container"}}{{/crossLink}} will cause events on the Container to not fire when that child is + * clicked. Setting this property to `false` does not prevent the {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}} + * method from returning the child. + * + * Note: In EaselJS 0.7.0, the mouseEnabled property will not work properly with nested Containers. Please + * check out the latest NEXT version in GitHub for an updated version with this issue resolved. The fix will be + * provided in the next release of EaselJS. + * @property mouseEnabled + * @type {Boolean} + * @default true + **/ + this.mouseEnabled = true; + + /** + * If false, the tick will not run on this display object (or its children). This can provide some performance benefits. + * In addition to preventing the "tick" event from being dispatched, it will also prevent tick related updates + * on some display objects (ex. Sprite & MovieClip frame advancing, DOMElement visibility handling). + * @property tickEnabled + * @type Boolean + * @default true + **/ + this.tickEnabled = true; + + /** + * An optional name for this display object. Included in {{#crossLink "DisplayObject/toString"}}{{/crossLink}} . Useful for + * debugging. + * @property name + * @type {String} + * @default null + **/ + this.name = null; + + /** + * A reference to the {{#crossLink "Container"}}{{/crossLink}} or {{#crossLink "Stage"}}{{/crossLink}} object that + * contains this display object, or null if it has not been added + * to one. + * @property parent + * @final + * @type {Container} + * @default null + * @readonly + **/ + this.parent = null; + + /** + * The left offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate + * around its center, you would set regX and {{#crossLink "DisplayObject/regY:property"}}{{/crossLink}} to 50. + * @property regX + * @type {Number} + * @default 0 + **/ + this.regX = 0; + + /** + * The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around + * its center, you would set {{#crossLink "DisplayObject/regX:property"}}{{/crossLink}} and regY to 50. + * @property regY + * @type {Number} + * @default 0 + **/ + this.regY = 0; + + /** + * The rotation in degrees for this display object. + * @property rotation + * @type {Number} + * @default 0 + **/ + this.rotation = 0; + + /** + * The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display + * object to twice its nominal width. To horizontally flip an object, set the scale to a negative number. + * @property scaleX + * @type {Number} + * @default 1 + **/ + this.scaleX = 1; + + /** + * The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display + * object to half its nominal height. To vertically flip an object, set the scale to a negative number. + * @property scaleY + * @type {Number} + * @default 1 + **/ + this.scaleY = 1; + + /** + * The factor to skew this display object horizontally. + * @property skewX + * @type {Number} + * @default 0 + **/ + this.skewX = 0; + + /** + * The factor to skew this display object vertically. + * @property skewY + * @type {Number} + * @default 0 + **/ + this.skewY = 0; + + /** + * A shadow object that defines the shadow to render on this display object. Set to `null` to remove a shadow. If + * null, this property is inherited from the parent container. + * @property shadow + * @type {Shadow} + * @default null + **/ + this.shadow = null; + + /** + * Indicates whether this display object should be rendered to the canvas and included when running the Stage + * {{#crossLink "Stage/getObjectsUnderPoint"}}{{/crossLink}} method. + * @property visible + * @type {Boolean} + * @default true + **/ + this.visible = true; + + /** + * The x (horizontal) position of the display object, relative to its parent. + * @property x + * @type {Number} + * @default 0 + **/ + this.x = 0; + + /** The y (vertical) position of the display object, relative to its parent. + * @property y + * @type {Number} + * @default 0 + **/ + this.y = 0; + + /** + * If set, defines the transformation for this display object, overriding all other transformation properties + * (x, y, rotation, scale, skew). + * @property transformMatrix + * @type {Matrix2D} + * @default null + **/ + this.transformMatrix = null; + + /** + * The composite operation indicates how the pixels of this display object will be composited with the elements + * behind it. If `null`, this property is inherited from the parent container. For more information, read the + * + * whatwg spec on compositing. + * @property compositeOperation + * @type {String} + * @default null + **/ + this.compositeOperation = null; + + /** + * Indicates whether the display object should be drawn to a whole pixel when + * {{#crossLink "Stage/snapToPixelEnabled"}}{{/crossLink}} is true. To enable/disable snapping on whole + * categories of display objects, set this value on the prototype (Ex. Text.prototype.snapToPixel = true). + * @property snapToPixel + * @type {Boolean} + * @default true + **/ + this.snapToPixel = true; + + /** + * An array of Filter objects to apply to this display object. Filters are only applied / updated when {{#crossLink "cache"}}{{/crossLink}} + * or {{#crossLink "updateCache"}}{{/crossLink}} is called on the display object, and only apply to the area that is + * cached. + * @property filters + * @type {Array} + * @default null + **/ + this.filters = null; + + /** + * A Shape instance that defines a vector mask (clipping path) for this display object. The shape's transformation + * will be applied relative to the display object's parent coordinates (as if it were a child of the parent). + * @property mask + * @type {Shape} + * @default null + */ + this.mask = null; + + /** + * A display object that will be tested when checking mouse interactions or testing {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}}. + * The hit area will have its transformation applied relative to this display object's coordinate space (as though + * the hit test object were a child of this display object and relative to its regX/Y). The hitArea will be tested + * using only its own `alpha` value regardless of the alpha value on the target display object, or the target's + * ancestors (parents). + * + * If set on a {{#crossLink "Container"}}{{/crossLink}}, children of the Container will not receive mouse events. + * This is similar to setting {{#crossLink "mouseChildren"}}{{/crossLink}} to false. + * + * Note that hitArea is NOT currently used by the `hitTest()` method, nor is it supported for {{#crossLink "Stage"}}{{/crossLink}}. + * @property hitArea + * @type {DisplayObject} + * @default null + */ + this.hitArea = null; + + /** + * A CSS cursor (ex. "pointer", "help", "text", etc) that will be displayed when the user hovers over this display + * object. You must enable mouseover events using the {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}} method to + * use this property. Setting a non-null cursor on a Container will override the cursor set on its descendants. + * @property cursor + * @type {String} + * @default null + */ + this.cursor = null; + + + // private properties: + /** + * @property _cacheOffsetX + * @protected + * @type {Number} + * @default 0 + **/ + this._cacheOffsetX = 0; + + /** + * @property _cacheOffsetY + * @protected + * @type {Number} + * @default 0 + **/ + this._cacheOffsetY = 0; + + /** + * @property _filterOffsetX + * @protected + * @type {Number} + * @default 0 + **/ + this._filterOffsetX = 0; + + /** + * @property _filterOffsetY + * @protected + * @type {Number} + * @default 0 + **/ + this._filterOffsetY = 0; + + /** + * @property _cacheScale + * @protected + * @type {Number} + * @default 1 + **/ + this._cacheScale = 1; + + /** + * @property _cacheDataURLID + * @protected + * @type {Number} + * @default 0 + */ + this._cacheDataURLID = 0; + + /** + * @property _cacheDataURL + * @protected + * @type {String} + * @default null + */ + this._cacheDataURL = null; + + /** + * @property _props + * @protected + * @type {DisplayObject} + * @default null + **/ + this._props = new createjs.DisplayProps(); + + /** + * @property _rectangle + * @protected + * @type {Rectangle} + * @default null + **/ + this._rectangle = new createjs.Rectangle(); + + /** + * @property _bounds + * @protected + * @type {Rectangle} + * @default null + **/ + this._bounds = null; + } + var p = createjs.extend(DisplayObject, createjs.EventDispatcher); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + +// static properties: + /** + * Listing of mouse event names. Used in _hasMouseEventListener. + * @property _MOUSE_EVENTS + * @protected + * @static + * @type {Array} + **/ + DisplayObject._MOUSE_EVENTS = ["click","dblclick","mousedown","mouseout","mouseover","pressmove","pressup","rollout","rollover"]; + + /** + * Suppresses errors generated when using features like hitTest, mouse events, and {{#crossLink "getObjectsUnderPoint"}}{{/crossLink}} + * with cross domain content. + * @property suppressCrossDomainErrors + * @static + * @type {Boolean} + * @default false + **/ + DisplayObject.suppressCrossDomainErrors = false; + + /** + * @property _snapToPixelEnabled + * @protected + * @static + * @type {Boolean} + * @default false + **/ + DisplayObject._snapToPixelEnabled = false; // stage.snapToPixelEnabled is temporarily copied here during a draw to provide global access. + + /** + * @property _hitTestCanvas + * @type {HTMLCanvasElement | Object} + * @static + * @protected + **/ + /** + * @property _hitTestContext + * @type {CanvasRenderingContext2D} + * @static + * @protected + **/ + var canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); // prevent errors on load in browsers without canvas. + if (canvas.getContext) { + DisplayObject._hitTestCanvas = canvas; + DisplayObject._hitTestContext = canvas.getContext("2d"); + canvas.width = canvas.height = 1; + } + + /** + * @property _nextCacheID + * @type {Number} + * @static + * @protected + **/ + DisplayObject._nextCacheID = 1; + + +// events: + /** + * Dispatched when the user presses their left mouse button over the display object. See the + * {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event mousedown + * @since 0.6.0 + */ + + /** + * Dispatched when the user presses their left mouse button and then releases it while over the display object. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event click + * @since 0.6.0 + */ + + /** + * Dispatched when the user double clicks their left mouse button over this display object. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event dblclick + * @since 0.6.0 + */ + + /** + * Dispatched when the user's mouse enters this display object. This event must be enabled using + * {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. See also {{#crossLink "DisplayObject/rollover:event"}}{{/crossLink}}. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event mouseover + * @since 0.6.0 + */ + + /** + * Dispatched when the user's mouse leaves this display object. This event must be enabled using + * {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. See also {{#crossLink "DisplayObject/rollout:event"}}{{/crossLink}}. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event mouseout + * @since 0.6.0 + */ + + /** + * This event is similar to {{#crossLink "DisplayObject/mouseover:event"}}{{/crossLink}}, with the following + * differences: it does not bubble, and it considers {{#crossLink "Container"}}{{/crossLink}} instances as an + * aggregate of their content. + * + * For example, myContainer contains two overlapping children: shapeA and shapeB. The user moves their mouse over + * shapeA and then directly on to shapeB. With a listener for {{#crossLink "mouseover:event"}}{{/crossLink}} on + * myContainer, two events would be received, each targeting a child element:
    + *
  1. when the mouse enters shapeA (target=shapeA)
  2. + *
  3. when the mouse enters shapeB (target=shapeB)
  4. + *
+ * However, with a listener for "rollover" instead, only a single event is received when the mouse first enters + * the aggregate myContainer content (target=myContainer). + * + * This event must be enabled using {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event rollover + * @since 0.7.0 + */ + + /** + * This event is similar to {{#crossLink "DisplayObject/mouseout:event"}}{{/crossLink}}, with the following + * differences: it does not bubble, and it considers {{#crossLink "Container"}}{{/crossLink}} instances as an + * aggregate of their content. + * + * For example, myContainer contains two overlapping children: shapeA and shapeB. The user moves their mouse over + * shapeA, then directly on to shapeB, then off both. With a listener for {{#crossLink "mouseout:event"}}{{/crossLink}} + * on myContainer, two events would be received, each targeting a child element:
    + *
  1. when the mouse leaves shapeA (target=shapeA)
  2. + *
  3. when the mouse leaves shapeB (target=shapeB)
  4. + *
+ * However, with a listener for "rollout" instead, only a single event is received when the mouse leaves + * the aggregate myContainer content (target=myContainer). + * + * This event must be enabled using {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event rollout + * @since 0.7.0 + */ + + /** + * After a {{#crossLink "DisplayObject/mousedown:event"}}{{/crossLink}} occurs on a display object, a pressmove + * event will be generated on that object whenever the mouse moves until the mouse press is released. This can be + * useful for dragging and similar operations. + * @event pressmove + * @since 0.7.0 + */ + + /** + * After a {{#crossLink "DisplayObject/mousedown:event"}}{{/crossLink}} occurs on a display object, a pressup event + * will be generated on that object when that mouse press is released. This can be useful for dragging and similar + * operations. + * @event pressup + * @since 0.7.0 + */ + + /** + * Dispatched when the display object is added to a parent container. + * @event added + */ + + /** + * Dispatched when the display object is removed from its parent container. + * @event removed + */ + + /** + * Dispatched on each display object on a stage whenever the stage updates. This occurs immediately before the + * rendering (draw) pass. When {{#crossLink "Stage/update"}}{{/crossLink}} is called, first all display objects on + * the stage dispatch the tick event, then all of the display objects are drawn to stage. Children will have their + * {{#crossLink "tick:event"}}{{/crossLink}} event dispatched in order of their depth prior to the event being + * dispatched on their parent. + * @event tick + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @param {Array} params An array containing any arguments that were passed to the Stage.update() method. For + * example if you called stage.update("hello"), then the params would be ["hello"]. + * @since 0.6.0 + */ + + +// getter / setters: + /** + * Use the {{#crossLink "DisplayObject/stage:property"}}{{/crossLink}} property instead. + * @method getStage + * @return {Stage} + * @deprecated + **/ + p.getStage = function() { + // uses dynamic access to avoid circular dependencies; + var o = this, _Stage = createjs["Stage"]; + while (o.parent) { o = o.parent; } + if (o instanceof _Stage) { return o; } + return null; + }; + + /** + * Returns the Stage instance that this display object will be rendered on, or null if it has not been added to one. + * @property stage + * @type {Stage} + * @readonly + **/ + try { + Object.defineProperties(p, { + stage: { get: p.getStage } + }); + } catch (e) {} + + +// public methods: + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. For example, + * used for drawing the cache (to prevent it from simply drawing an existing cache back into itself). + * @return {Boolean} + **/ + p.draw = function(ctx, ignoreCache) { + var cacheCanvas = this.cacheCanvas; + if (ignoreCache || !cacheCanvas) { return false; } + var scale = this._cacheScale; + ctx.drawImage(cacheCanvas, this._cacheOffsetX+this._filterOffsetX, this._cacheOffsetY+this._filterOffsetY, cacheCanvas.width/scale, cacheCanvas.height/scale); + return true; + }; + + /** + * Applies this display object's transformation, alpha, globalCompositeOperation, clipping path (mask), and shadow + * to the specified context. This is typically called prior to {{#crossLink "DisplayObject/draw"}}{{/crossLink}}. + * @method updateContext + * @param {CanvasRenderingContext2D} ctx The canvas 2D to update. + **/ + p.updateContext = function(ctx) { + var o=this, mask=o.mask, mtx= o._props.matrix; + + if (mask && mask.graphics && !mask.graphics.isEmpty()) { + mask.getMatrix(mtx); + ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty); + + mask.graphics.drawAsPath(ctx); + ctx.clip(); + + mtx.invert(); + ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty); + } + + this.getMatrix(mtx); + var tx = mtx.tx, ty = mtx.ty; + if (DisplayObject._snapToPixelEnabled && o.snapToPixel) { + tx = tx + (tx < 0 ? -0.5 : 0.5) | 0; + ty = ty + (ty < 0 ? -0.5 : 0.5) | 0; + } + ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, tx, ty); + ctx.globalAlpha *= o.alpha; + if (o.compositeOperation) { ctx.globalCompositeOperation = o.compositeOperation; } + if (o.shadow) { this._applyShadow(ctx, o.shadow); } + }; + + /** + * Draws the display object into a new canvas, which is then used for subsequent draws. For complex content + * that does not change frequently (ex. a Container with many children that do not move, or a complex vector Shape), + * this can provide for much faster rendering because the content does not need to be re-rendered each tick. The + * cached display object can be moved, rotated, faded, etc freely, however if its content changes, you must + * manually update the cache by calling updateCache() or cache() again. You must specify + * the cache area via the x, y, w, and h parameters. This defines the rectangle that will be rendered and cached + * using this display object's coordinates. + * + *

Example

+ * For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25: + * + * var shape = new createjs.Shape(); + * shape.graphics.beginFill("#ff0000").drawCircle(0, 0, 25); + * myShape.cache(-25, -25, 50, 50); + * + * Note that filters need to be defined before the cache is applied. Check out the {{#crossLink "Filter"}}{{/crossLink}} + * class for more information. Some filters (ex. BlurFilter) will not work as expected in conjunction with the scale param. + * + * Usually, the resulting cacheCanvas will have the dimensions width*scale by height*scale, however some filters (ex. BlurFilter) + * will add padding to the canvas dimensions. + * + * @method cache + * @param {Number} x The x coordinate origin for the cache region. + * @param {Number} y The y coordinate origin for the cache region. + * @param {Number} width The width of the cache region. + * @param {Number} height The height of the cache region. + * @param {Number} [scale=1] The scale at which the cache will be created. For example, if you cache a vector shape using + * myShape.cache(0,0,100,100,2) then the resulting cacheCanvas will be 200x200 px. This lets you scale and rotate + * cached elements with greater fidelity. Default is 1. + **/ + p.cache = function(x, y, width, height, scale) { + // draw to canvas. + scale = scale||1; + if (!this.cacheCanvas) { this.cacheCanvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); } + this._cacheWidth = width; + this._cacheHeight = height; + this._cacheOffsetX = x; + this._cacheOffsetY = y; + this._cacheScale = scale; + this.updateCache(); + }; + + /** + * Redraws the display object to its cache. Calling updateCache without an active cache will throw an error. + * If compositeOperation is null the current cache will be cleared prior to drawing. Otherwise the display object + * will be drawn over the existing cache using the specified compositeOperation. + * + *

Example

+ * Clear the current graphics of a cached shape, draw some new instructions, and then update the cache. The new line + * will be drawn on top of the old one. + * + * // Not shown: Creating the shape, and caching it. + * shapeInstance.clear(); + * shapeInstance.setStrokeStyle(3).beginStroke("#ff0000").moveTo(100, 100).lineTo(200,200); + * shapeInstance.updateCache(); + * + * @method updateCache + * @param {String} compositeOperation The compositeOperation to use, or null to clear the cache and redraw it. + * + * whatwg spec on compositing. + **/ + p.updateCache = function(compositeOperation) { + var cacheCanvas = this.cacheCanvas; + if (!cacheCanvas) { throw "cache() must be called before updateCache()"; } + var scale = this._cacheScale, offX = this._cacheOffsetX*scale, offY = this._cacheOffsetY*scale; + var w = this._cacheWidth, h = this._cacheHeight, ctx = cacheCanvas.getContext("2d"); + + var fBounds = this._getFilterBounds(); + offX += (this._filterOffsetX = fBounds.x); + offY += (this._filterOffsetY = fBounds.y); + + w = Math.ceil(w*scale) + fBounds.width; + h = Math.ceil(h*scale) + fBounds.height; + if (w != cacheCanvas.width || h != cacheCanvas.height) { + // TODO: it would be nice to preserve the content if there is a compositeOperation. + cacheCanvas.width = w; + cacheCanvas.height = h; + } else if (!compositeOperation) { + ctx.clearRect(0, 0, w+1, h+1); + } + + ctx.save(); + ctx.globalCompositeOperation = compositeOperation; + ctx.setTransform(scale, 0, 0, scale, -offX, -offY); + this.draw(ctx, true); + // TODO: filters and cache scale don't play well together at present. + this._applyFilters(); + ctx.restore(); + this.cacheID = DisplayObject._nextCacheID++; + }; + + /** + * Clears the current cache. See {{#crossLink "DisplayObject/cache"}}{{/crossLink}} for more information. + * @method uncache + **/ + p.uncache = function() { + this._cacheDataURL = this.cacheCanvas = null; + this.cacheID = this._cacheOffsetX = this._cacheOffsetY = this._filterOffsetX = this._filterOffsetY = 0; + this._cacheScale = 1; + }; + + /** + * Returns a data URL for the cache, or null if this display object is not cached. + * Uses cacheID to ensure a new data URL is not generated if the cache has not changed. + * @method getCacheDataURL + * @return {String} The image data url for the cache. + **/ + p.getCacheDataURL = function() { + if (!this.cacheCanvas) { return null; } + if (this.cacheID != this._cacheDataURLID) { this._cacheDataURL = this.cacheCanvas.toDataURL(); } + return this._cacheDataURL; + }; + + /** + * Transforms the specified x and y position from the coordinate space of the display object + * to the global (stage) coordinate space. For example, this could be used to position an HTML label + * over a specific point on a nested display object. Returns a Point instance with x and y properties + * correlating to the transformed coordinates on the stage. + * + *

Example

+ * + * displayObject.x = 300; + * displayObject.y = 200; + * stage.addChild(displayObject); + * var point = displayObject.localToGlobal(100, 100); + * // Results in x=400, y=300 + * + * @method localToGlobal + * @param {Number} x The x position in the source display object to transform. + * @param {Number} y The y position in the source display object to transform. + * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. + * @return {Point} A Point instance with x and y properties correlating to the transformed coordinates + * on the stage. + **/ + p.localToGlobal = function(x, y, pt) { + return this.getConcatenatedMatrix(this._props.matrix).transformPoint(x,y, pt||new createjs.Point()); + }; + + /** + * Transforms the specified x and y position from the global (stage) coordinate space to the + * coordinate space of the display object. For example, this could be used to determine + * the current mouse position within the display object. Returns a Point instance with x and y properties + * correlating to the transformed position in the display object's coordinate space. + * + *

Example

+ * + * displayObject.x = 300; + * displayObject.y = 200; + * stage.addChild(displayObject); + * var point = displayObject.globalToLocal(100, 100); + * // Results in x=-200, y=-100 + * + * @method globalToLocal + * @param {Number} x The x position on the stage to transform. + * @param {Number} y The y position on the stage to transform. + * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. + * @return {Point} A Point instance with x and y properties correlating to the transformed position in the + * display object's coordinate space. + **/ + p.globalToLocal = function(x, y, pt) { + return this.getConcatenatedMatrix(this._props.matrix).invert().transformPoint(x,y, pt||new createjs.Point()); + }; + + /** + * Transforms the specified x and y position from the coordinate space of this display object to the coordinate + * space of the target display object. Returns a Point instance with x and y properties correlating to the + * transformed position in the target's coordinate space. Effectively the same as using the following code with + * {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} and {{#crossLink "DisplayObject/globalToLocal"}}{{/crossLink}}. + * + * var pt = this.localToGlobal(x, y); + * pt = target.globalToLocal(pt.x, pt.y); + * + * @method localToLocal + * @param {Number} x The x position in the source display object to transform. + * @param {Number} y The y position on the source display object to transform. + * @param {DisplayObject} target The target display object to which the coordinates will be transformed. + * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. + * @return {Point} Returns a Point instance with x and y properties correlating to the transformed position + * in the target's coordinate space. + **/ + p.localToLocal = function(x, y, target, pt) { + pt = this.localToGlobal(x, y, pt); + return target.globalToLocal(pt.x, pt.y, pt); + }; + + /** + * Shortcut method to quickly set the transform properties on the display object. All parameters are optional. + * Omitted parameters will have the default value set. + * + *

Example

+ * + * displayObject.setTransform(100, 100, 2, 2); + * + * @method setTransform + * @param {Number} [x=0] The horizontal translation (x position) in pixels + * @param {Number} [y=0] The vertical translation (y position) in pixels + * @param {Number} [scaleX=1] The horizontal scale, as a percentage of 1 + * @param {Number} [scaleY=1] the vertical scale, as a percentage of 1 + * @param {Number} [rotation=0] The rotation, in degrees + * @param {Number} [skewX=0] The horizontal skew factor + * @param {Number} [skewY=0] The vertical skew factor + * @param {Number} [regX=0] The horizontal registration point in pixels + * @param {Number} [regY=0] The vertical registration point in pixels + * @return {DisplayObject} Returns this instance. Useful for chaining commands. + * @chainable + */ + p.setTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { + this.x = x || 0; + this.y = y || 0; + this.scaleX = scaleX == null ? 1 : scaleX; + this.scaleY = scaleY == null ? 1 : scaleY; + this.rotation = rotation || 0; + this.skewX = skewX || 0; + this.skewY = skewY || 0; + this.regX = regX || 0; + this.regY = regY || 0; + return this; + }; + + /** + * Returns a matrix based on this object's current transform. + * @method getMatrix + * @param {Matrix2D} matrix Optional. A Matrix2D object to populate with the calculated values. If null, a new + * Matrix object is returned. + * @return {Matrix2D} A matrix representing this display object's transform. + **/ + p.getMatrix = function(matrix) { + var o = this, mtx = matrix&&matrix.identity() || new createjs.Matrix2D(); + return o.transformMatrix ? mtx.copy(o.transformMatrix) : mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.regX, o.regY); + }; + + /** + * Generates a Matrix2D object representing the combined transform of the display object and all of its + * parent Containers up to the highest level ancestor (usually the {{#crossLink "Stage"}}{{/crossLink}}). This can + * be used to transform positions between coordinate spaces, such as with {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} + * and {{#crossLink "DisplayObject/globalToLocal"}}{{/crossLink}}. + * @method getConcatenatedMatrix + * @param {Matrix2D} [matrix] A {{#crossLink "Matrix2D"}}{{/crossLink}} object to populate with the calculated values. + * If null, a new Matrix2D object is returned. + * @return {Matrix2D} The combined matrix. + **/ + p.getConcatenatedMatrix = function(matrix) { + var o = this, mtx = this.getMatrix(matrix); + while (o = o.parent) { + mtx.prependMatrix(o.getMatrix(o._props.matrix)); + } + return mtx; + }; + + /** + * Generates a DisplayProps object representing the combined display properties of the object and all of its + * parent Containers up to the highest level ancestor (usually the {{#crossLink "Stage"}}{{/crossLink}}). + * @method getConcatenatedDisplayProps + * @param {DisplayProps} [props] A {{#crossLink "DisplayProps"}}{{/crossLink}} object to populate with the calculated values. + * If null, a new DisplayProps object is returned. + * @return {DisplayProps} The combined display properties. + **/ + p.getConcatenatedDisplayProps = function(props) { + props = props ? props.identity() : new createjs.DisplayProps(); + var o = this, mtx = o.getMatrix(props.matrix); + do { + props.prepend(o.visible, o.alpha, o.shadow, o.compositeOperation); + + // we do this to avoid problems with the matrix being used for both operations when o._props.matrix is passed in as the props param. + // this could be simplified (ie. just done as part of the prepend above) if we switched to using a pool. + if (o != this) { mtx.prependMatrix(o.getMatrix(o._props.matrix)); } + } while (o = o.parent); + return props; + }; + + /** + * Tests whether the display object intersects the specified point in local coordinates (ie. draws a pixel + * with alpha > 0 at the specified position). This ignores the alpha, shadow, hitArea, mask, and compositeOperation + * of the display object. + * + *

Example

+ * + * var myShape = new createjs.Shape(); + * myShape.graphics.beginFill("red").drawRect(100, 100, 20, 50); + * + * console.log(myShape.hitTest(10,10); // false + * console.log(myShape.hitTest(110, 25); // true + * + * Note that to use Stage coordinates (such as {{#crossLink "Stage/mouseX:property"}}{{/crossLink}}), they must + * first be converted to local coordinates: + * + * stage.addEventListener("stagemousedown", handleMouseDown); + * function handleMouseDown(event) { + * var p = myShape.globalToLocal(stage.mouseX, stage.mouseY); + * var hit = myShape.hitTest(p.x, p.y); + * } + * + * Shape-to-shape collision is not currently supported by EaselJS. + * + * @method hitTest + * @param {Number} x The x position to check in the display object's local coordinates. + * @param {Number} y The y position to check in the display object's local coordinates. + * @return {Boolean} A Boolean indicating whether a visible portion of the DisplayObject intersect the specified + * local Point. + */ + p.hitTest = function(x, y) { + var ctx = DisplayObject._hitTestContext; + ctx.setTransform(1, 0, 0, 1, -x, -y); + this.draw(ctx); + + var hit = this._testHit(ctx); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, 2, 2); + return hit; + }; + + /** + * Provides a chainable shortcut method for setting a number of properties on the instance. + * + *

Example

+ * + * var myGraphics = new createjs.Graphics().beginFill("#ff0000").drawCircle(0, 0, 25); + * var shape = stage.addChild(new createjs.Shape()).set({graphics:myGraphics, x:100, y:100, alpha:0.5}); + * + * @method set + * @param {Object} props A generic object containing properties to copy to the DisplayObject instance. + * @return {DisplayObject} Returns the instance the method is called on (useful for chaining calls.) + * @chainable + */ + p.set = function(props) { + for (var n in props) { this[n] = props[n]; } + return this; + }; + + /** + * Returns a rectangle representing this object's bounds in its local coordinate system (ie. with no transformation). + * Objects that have been cached will return the bounds of the cache. + * + * Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use + * {{#crossLink "DisplayObject/setBounds"}}{{/crossLink}} so that they are included when calculating Container + * bounds. + * + * + * + * + * + * + * + * + * + *
All + * All display objects support setting bounds manually using setBounds(). Likewise, display objects that + * have been cached using cache() will return the bounds of their cache. Manual and cache bounds will override + * the automatic calculations listed below. + *
Bitmap + * Returns the width and height of the sourceRect (if specified) or image, extending from (x=0,y=0). + *
Sprite + * Returns the bounds of the current frame. May have non-zero x/y if a frame registration point was specified + * in the spritesheet data. See also {{#crossLink "SpriteSheet/getFrameBounds"}}{{/crossLink}} + *
Container + * Returns the aggregate (combined) bounds of all children that return a non-null value from getBounds(). + *
Shape + * Does not currently support automatic bounds calculations. Use setBounds() to manually define bounds. + *
Text + * Returns approximate bounds. Horizontal values (x/width) are quite accurate, but vertical values (y/height) are + * not, especially when using textBaseline values other than "top". + *
BitmapText + * Returns approximate bounds. Values will be more accurate if spritesheet frame registration points are close + * to (x=0,y=0). + *
+ * + * Bounds can be expensive to calculate for some objects (ex. text, or containers with many children), and + * are recalculated each time you call getBounds(). You can prevent recalculation on static objects by setting the + * bounds explicitly: + * + * var bounds = obj.getBounds(); + * obj.setBounds(bounds.x, bounds.y, bounds.width, bounds.height); + * // getBounds will now use the set values, instead of recalculating + * + * To reduce memory impact, the returned Rectangle instance may be reused internally; clone the instance or copy its + * values if you need to retain it. + * + * var myBounds = obj.getBounds().clone(); + * // OR: + * myRect.copy(obj.getBounds()); + * + * @method getBounds + * @return {Rectangle} A Rectangle instance representing the bounds, or null if bounds are not available for this + * object. + **/ + p.getBounds = function() { + if (this._bounds) { return this._rectangle.copy(this._bounds); } + var cacheCanvas = this.cacheCanvas; + if (cacheCanvas) { + var scale = this._cacheScale; + return this._rectangle.setValues(this._cacheOffsetX, this._cacheOffsetY, cacheCanvas.width/scale, cacheCanvas.height/scale); + } + return null; + }; + + /** + * Returns a rectangle representing this object's bounds in its parent's coordinate system (ie. with transformations applied). + * Objects that have been cached will return the transformed bounds of the cache. + * + * Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use + * {{#crossLink "DisplayObject/setBounds"}}{{/crossLink}} so that they are included when calculating Container + * bounds. + * + * To reduce memory impact, the returned Rectangle instance may be reused internally; clone the instance or copy its + * values if you need to retain it. + * + * Container instances calculate aggregate bounds for all children that return bounds via getBounds. + * @method getTransformedBounds + * @return {Rectangle} A Rectangle instance representing the bounds, or null if bounds are not available for this object. + **/ + p.getTransformedBounds = function() { + return this._getBounds(); + }; + + /** + * Allows you to manually specify the bounds of an object that either cannot calculate their own bounds (ex. Shape & + * Text) for future reference, or so the object can be included in Container bounds. Manually set bounds will always + * override calculated bounds. + * + * The bounds should be specified in the object's local (untransformed) coordinates. For example, a Shape instance + * with a 25px radius circle centered at 0,0 would have bounds of (-25, -25, 50, 50). + * @method setBounds + * @param {Number} x The x origin of the bounds. Pass null to remove the manual bounds. + * @param {Number} y The y origin of the bounds. + * @param {Number} width The width of the bounds. + * @param {Number} height The height of the bounds. + **/ + p.setBounds = function(x, y, width, height) { + if (x == null) { this._bounds = x; } + this._bounds = (this._bounds || new createjs.Rectangle()).setValues(x, y, width, height); + }; + + /** + * Returns a clone of this DisplayObject. Some properties that are specific to this instance's current context are + * reverted to their defaults (for example .parent). Caches are not maintained across clones, and some elements + * are copied by reference (masks, individual filter instances, hit area) + * @method clone + * @return {DisplayObject} A clone of the current DisplayObject instance. + **/ + p.clone = function() { + return this._cloneProps(new DisplayObject()); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[DisplayObject (name="+ this.name +")]"; + }; + + +// private methods: + // separated so it can be used more easily in subclasses: + /** + * @method _cloneProps + * @param {DisplayObject} o The DisplayObject instance which will have properties from the current DisplayObject + * instance copied into. + * @return {DisplayObject} o + * @protected + **/ + p._cloneProps = function(o) { + o.alpha = this.alpha; + o.mouseEnabled = this.mouseEnabled; + o.tickEnabled = this.tickEnabled; + o.name = this.name; + o.regX = this.regX; + o.regY = this.regY; + o.rotation = this.rotation; + o.scaleX = this.scaleX; + o.scaleY = this.scaleY; + o.shadow = this.shadow; + o.skewX = this.skewX; + o.skewY = this.skewY; + o.visible = this.visible; + o.x = this.x; + o.y = this.y; + o.compositeOperation = this.compositeOperation; + o.snapToPixel = this.snapToPixel; + o.filters = this.filters==null?null:this.filters.slice(0); + o.mask = this.mask; + o.hitArea = this.hitArea; + o.cursor = this.cursor; + o._bounds = this._bounds; + return o; + }; + + /** + * @method _applyShadow + * @protected + * @param {CanvasRenderingContext2D} ctx + * @param {Shadow} shadow + **/ + p._applyShadow = function(ctx, shadow) { + shadow = shadow || Shadow.identity; + ctx.shadowColor = shadow.color; + ctx.shadowOffsetX = shadow.offsetX; + ctx.shadowOffsetY = shadow.offsetY; + ctx.shadowBlur = shadow.blur; + }; + + + /** + * @method _tick + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * @protected + **/ + p._tick = function(evtObj) { + // because tick can be really performance sensitive, check for listeners before calling dispatchEvent. + var ls = this._listeners; + if (ls && ls["tick"]) { + // reset & reuse the event object to avoid construction / GC costs: + evtObj.target = null; + evtObj.propagationStopped = evtObj.immediatePropagationStopped = false; + this.dispatchEvent(evtObj); + } + }; + + /** + * @method _testHit + * @protected + * @param {CanvasRenderingContext2D} ctx + * @return {Boolean} + **/ + p._testHit = function(ctx) { + try { + var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1; + } catch (e) { + if (!DisplayObject.suppressCrossDomainErrors) { + throw "An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images."; + } + } + return hit; + }; + + /** + * @method _applyFilters + * @protected + **/ + p._applyFilters = function() { + if (!this.filters || this.filters.length == 0 || !this.cacheCanvas) { return; } + var l = this.filters.length; + var ctx = this.cacheCanvas.getContext("2d"); + var w = this.cacheCanvas.width; + var h = this.cacheCanvas.height; + for (var i=0; i maxX) { maxX = x; } + if ((x = x_a + y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; } + if ((x = y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; } + + if ((y = x_b + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } + if ((y = x_b + y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } + if ((y = y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } + + return bounds.setValues(minX, minY, maxX-minX, maxY-minY); + }; + + /** + * Indicates whether the display object has any mouse event listeners or a cursor. + * @method _isMouseOpaque + * @return {Boolean} + * @protected + **/ + p._hasMouseEventListener = function() { + var evts = DisplayObject._MOUSE_EVENTS; + for (var i= 0, l=evts.length; itransform and alpha properties concatenated with their parent + * Container. + * + * For example, a {{#crossLink "Shape"}}{{/crossLink}} with x=100 and alpha=0.5, placed in a Container with x=50 + * and alpha=0.7 will be rendered to the canvas at x=150 and alpha=0.35. + * Containers have some overhead, so you generally shouldn't create a Container to hold a single child. + * + *

Example

+ * + * var container = new createjs.Container(); + * container.addChild(bitmapInstance, shapeInstance); + * container.x = 100; + * + * @class Container + * @extends DisplayObject + * @constructor + **/ + function Container() { + this.DisplayObject_constructor(); + + // public properties: + /** + * The array of children in the display list. You should usually use the child management methods such as + * {{#crossLink "Container/addChild"}}{{/crossLink}}, {{#crossLink "Container/removeChild"}}{{/crossLink}}, + * {{#crossLink "Container/swapChildren"}}{{/crossLink}}, etc, rather than accessing this directly, but it is + * included for advanced uses. + * @property children + * @type Array + * @default null + **/ + this.children = []; + + /** + * Indicates whether the children of this container are independently enabled for mouse/pointer interaction. + * If false, the children will be aggregated under the container - for example, a click on a child shape would + * trigger a click event on the container. + * @property mouseChildren + * @type Boolean + * @default true + **/ + this.mouseChildren = true; + + /** + * If false, the tick will not be propagated to children of this Container. This can provide some performance benefits. + * In addition to preventing the "tick" event from being dispatched, it will also prevent tick related updates + * on some display objects (ex. Sprite & MovieClip frame advancing, DOMElement visibility handling). + * @property tickChildren + * @type Boolean + * @default true + **/ + this.tickChildren = true; + } + var p = createjs.extend(Container, createjs.DisplayObject); + + +// getter / setters: + /** + * Use the {{#crossLink "Container/numChildren:property"}}{{/crossLink}} property instead. + * @method getNumChildren + * @return {Number} + * @deprecated + **/ + p.getNumChildren = function() { + return this.children.length; + }; + + /** + * Returns the number of children in the container. + * @property numChildren + * @type {Number} + * @readonly + **/ + try { + Object.defineProperties(p, { + numChildren: { get: p.getNumChildren } + }); + } catch (e) {} + + +// public methods: + /** + * Constructor alias for backwards compatibility. This method will be removed in future versions. + * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. + * @method initialize + * @deprecated in favour of `createjs.promote()` + **/ + p.initialize = Container; // TODO: deprecated. + + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var hasContent = this.cacheCanvas || this.children.length; + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + + // this ensures we don't have issues with display list changes that occur during a draw: + var list = this.children.slice(); + for (var i=0,l=list.length; iExample + * + * container.addChild(bitmapInstance); + * + * You can also add multiple children at once: + * + * container.addChild(bitmapInstance, shapeInstance, textInstance); + * + * @method addChild + * @param {DisplayObject} child The display object to add. + * @return {DisplayObject} The child that was added, or the last child if multiple children were added. + **/ + p.addChild = function(child) { + if (child == null) { return child; } + var l = arguments.length; + if (l > 1) { + for (var i=0; iExample + * + * addChildAt(child1, index); + * + * You can also add multiple children, such as: + * + * addChildAt(child1, child2, ..., index); + * + * The index must be between 0 and numChildren. For example, to add myShape under otherShape in the display list, + * you could use: + * + * container.addChildAt(myShape, container.getChildIndex(otherShape)); + * + * This would also bump otherShape's index up by one. Fails silently if the index is out of range. + * + * @method addChildAt + * @param {DisplayObject} child The display object to add. + * @param {Number} index The index to add the child at. + * @return {DisplayObject} Returns the last child that was added, or the last child if multiple children were added. + **/ + p.addChildAt = function(child, index) { + var l = arguments.length; + var indx = arguments[l-1]; // can't use the same name as the index param or it replaces arguments[1] + if (indx < 0 || indx > this.children.length) { return arguments[l-2]; } + if (l > 2) { + for (var i=0; iExample + * + * container.removeChild(child); + * + * You can also remove multiple children: + * + * removeChild(child1, child2, ...); + * + * Returns true if the child (or children) was removed, or false if it was not in the display list. + * @method removeChild + * @param {DisplayObject} child The child to remove. + * @return {Boolean} true if the child (or children) was removed, or false if it was not in the display list. + **/ + p.removeChild = function(child) { + var l = arguments.length; + if (l > 1) { + var good = true; + for (var i=0; iExample + * + * container.removeChildAt(2); + * + * You can also remove multiple children: + * + * container.removeChild(2, 7, ...) + * + * Returns true if the child (or children) was removed, or false if any index was out of range. + * @method removeChildAt + * @param {Number} index The index of the child to remove. + * @return {Boolean} true if the child (or children) was removed, or false if any index was out of range. + **/ + p.removeChildAt = function(index) { + var l = arguments.length; + if (l > 1) { + var a = []; + for (var i=0; i this.children.length-1) { return false; } + var child = this.children[index]; + if (child) { child.parent = null; } + this.children.splice(index, 1); + child.dispatchEvent("removed"); + return true; + }; + + /** + * Removes all children from the display list. + * + *

Example

+ * + * container.removeAllChildren(); + * + * @method removeAllChildren + **/ + p.removeAllChildren = function() { + var kids = this.children; + while (kids.length) { this.removeChildAt(0); } + }; + + /** + * Returns the child at the specified index. + * + *

Example

+ * + * container.getChildAt(2); + * + * @method getChildAt + * @param {Number} index The index of the child to return. + * @return {DisplayObject} The child at the specified index. Returns null if there is no child at the index. + **/ + p.getChildAt = function(index) { + return this.children[index]; + }; + + /** + * Returns the child with the specified name. + * @method getChildByName + * @param {String} name The name of the child to return. + * @return {DisplayObject} The child with the specified name. + **/ + p.getChildByName = function(name) { + var kids = this.children; + for (var i=0,l=kids.length;iExample: Display children with a higher y in front. + * + * var sortFunction = function(obj1, obj2, options) { + * if (obj1.y > obj2.y) { return 1; } + * if (obj1.y < obj2.y) { return -1; } + * return 0; + * } + * container.sortChildren(sortFunction); + * + * @method sortChildren + * @param {Function} sortFunction the function to use to sort the child list. See JavaScript's Array.sort + * documentation for details. + **/ + p.sortChildren = function(sortFunction) { + this.children.sort(sortFunction); + }; + + /** + * Returns the index of the specified child in the display list, or -1 if it is not in the display list. + * + *

Example

+ * + * var index = container.getChildIndex(child); + * + * @method getChildIndex + * @param {DisplayObject} child The child to return the index of. + * @return {Number} The index of the specified child. -1 if the child is not found. + **/ + p.getChildIndex = function(child) { + return createjs.indexOf(this.children, child); + }; + + /** + * Swaps the children at the specified indexes. Fails silently if either index is out of range. + * @method swapChildrenAt + * @param {Number} index1 + * @param {Number} index2 + **/ + p.swapChildrenAt = function(index1, index2) { + var kids = this.children; + var o1 = kids[index1]; + var o2 = kids[index2]; + if (!o1 || !o2) { return; } + kids[index1] = o2; + kids[index2] = o1; + }; + + /** + * Swaps the specified children's depth in the display list. Fails silently if either child is not a child of this + * Container. + * @method swapChildren + * @param {DisplayObject} child1 + * @param {DisplayObject} child2 + **/ + p.swapChildren = function(child1, child2) { + var kids = this.children; + var index1,index2; + for (var i=0,l=kids.length;i= l) { return; } + for (var i=0;i 0 at the + * specified position). This ignores the alpha, shadow and compositeOperation of the display object, and all + * transform properties including regX/Y. + * @method hitTest + * @param {Number} x The x position to check in the display object's local coordinates. + * @param {Number} y The y position to check in the display object's local coordinates. + * @return {Boolean} A Boolean indicating whether there is a visible section of a DisplayObject that overlaps the specified + * coordinates. + **/ + p.hitTest = function(x, y) { + // TODO: optimize to use the fast cache check where possible. + return (this.getObjectUnderPoint(x, y) != null); + }; + + /** + * Returns an array of all display objects under the specified coordinates that are in this container's display + * list. This routine ignores any display objects with {{#crossLink "DisplayObject/mouseEnabled:property"}}{{/crossLink}} + * set to `false`. The array will be sorted in order of visual depth, with the top-most display object at index 0. + * This uses shape based hit detection, and can be an expensive operation to run, so it is best to use it carefully. + * For example, if testing for objects under the mouse, test on tick (instead of on {{#crossLink "DisplayObject/mousemove:event"}}{{/crossLink}}), + * and only if the mouse's position has changed. + * + *
    + *
  • By default (mode=0) this method evaluates all display objects.
  • + *
  • By setting the `mode` parameter to `1`, the {{#crossLink "DisplayObject/mouseEnabled:property"}}{{/crossLink}} + * and {{#crossLink "mouseChildren:property"}}{{/crossLink}} properties will be respected.
  • + *
  • Setting the `mode` to `2` additionally excludes display objects that do not have active mouse event + * listeners or a {{#crossLink "DisplayObject:cursor:property"}}{{/crossLink}} property. That is, only objects + * that would normally intercept mouse interaction will be included. This can significantly improve performance + * in some cases by reducing the number of display objects that need to be tested.
  • + * + * + * This method accounts for both {{#crossLink "DisplayObject/hitArea:property"}}{{/crossLink}} and {{#crossLink "DisplayObject/mask:property"}}{{/crossLink}}. + * @method getObjectsUnderPoint + * @param {Number} x The x position in the container to test. + * @param {Number} y The y position in the container to test. + * @param {Number} [mode=0] The mode to use to determine which display objects to include. 0-all, 1-respect mouseEnabled/mouseChildren, 2-only mouse opaque objects. + * @return {Array} An Array of DisplayObjects under the specified coordinates. + **/ + p.getObjectsUnderPoint = function(x, y, mode) { + var arr = []; + var pt = this.localToGlobal(x, y); + this._getObjectsUnderPoint(pt.x, pt.y, arr, mode>0, mode==1); + return arr; + }; + + /** + * Similar to {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}}, but returns only the top-most display + * object. This runs significantly faster than getObjectsUnderPoint(), but is still potentially an expensive + * operation. See {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}} for more information. + * @method getObjectUnderPoint + * @param {Number} x The x position in the container to test. + * @param {Number} y The y position in the container to test. + * @param {Number} mode The mode to use to determine which display objects to include. 0-all, 1-respect mouseEnabled/mouseChildren, 2-only mouse opaque objects. + * @return {DisplayObject} The top-most display object under the specified coordinates. + **/ + p.getObjectUnderPoint = function(x, y, mode) { + var pt = this.localToGlobal(x, y); + return this._getObjectsUnderPoint(pt.x, pt.y, null, mode>0, mode==1); + }; + + /** + * Docced in superclass. + */ + p.getBounds = function() { + return this._getBounds(null, true); + }; + + + /** + * Docced in superclass. + */ + p.getTransformedBounds = function() { + return this._getBounds(); + }; + + /** + * Returns a clone of this Container. Some properties that are specific to this instance's current context are + * reverted to their defaults (for example .parent). + * @method clone + * @param {Boolean} [recursive=false] If true, all of the descendants of this container will be cloned recursively. If false, the + * properties of the container will be cloned, but the new instance will not have any children. + * @return {Container} A clone of the current Container instance. + **/ + p.clone = function(recursive) { + var o = this._cloneProps(new Container()); + if (recursive) { this._cloneChildren(o); } + return o; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Container (name="+ this.name +")]"; + }; + + +// private methods: + /** + * @method _tick + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * @protected + **/ + p._tick = function(evtObj) { + if (this.tickChildren) { + for (var i=this.children.length-1; i>=0; i--) { + var child = this.children[i]; + if (child.tickEnabled && child._tick) { child._tick(evtObj); } + } + } + this.DisplayObject__tick(evtObj); + }; + + /** + * Recursively clones all children of this container, and adds them to the target container. + * @method cloneChildren + * @protected + * @param {Container} o The target container. + **/ + p._cloneChildren = function(o) { + if (o.children.length) { o.removeAllChildren(); } + var arr = o.children; + for (var i=0, l=this.children.length; i=0; i--) { + var child = children[i]; + var hitArea = child.hitArea; + if (!child.visible || (!hitArea && !child.isVisible()) || (mouse && !child.mouseEnabled)) { continue; } + if (!hitArea && !this._testMask(child, x, y)) { continue; } + + // if a child container has a hitArea then we only need to check its hitArea, so we can treat it as a normal DO: + if (!hitArea && child instanceof Container) { + var result = child._getObjectsUnderPoint(x, y, arr, mouse, activeListener, currentDepth+1); + if (!arr && result) { return (mouse && !this.mouseChildren) ? this : result; } + } else { + if (mouse && !activeListener && !child._hasMouseEventListener()) { continue; } + + // TODO: can we pass displayProps forward, to avoid having to calculate this backwards every time? It's kind of a mixed bag. When we're only hunting for DOs with event listeners, it may not make sense. + var props = child.getConcatenatedDisplayProps(child._props); + mtx = props.matrix; + + if (hitArea) { + mtx.appendMatrix(hitArea.getMatrix(hitArea._props.matrix)); + props.alpha = hitArea.alpha; + } + + ctx.globalAlpha = props.alpha; + ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx-x, mtx.ty-y); + (hitArea||child).draw(ctx); + if (!this._testHit(ctx)) { continue; } + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, 2, 2); + if (arr) { arr.push(child); } + else { return (mouse && !this.mouseChildren) ? this : child; } + } + } + return null; + }; + + /** + * @method _testMask + * @param {DisplayObject} target + * @param {Number} x + * @param {Number} y + * @return {Boolean} Indicates whether the x/y is within the masked region. + * @protected + **/ + p._testMask = function(target, x, y) { + var mask = target.mask; + if (!mask || !mask.graphics || mask.graphics.isEmpty()) { return true; } + + var mtx = this._props.matrix, parent = target.parent; + mtx = parent ? parent.getConcatenatedMatrix(mtx) : mtx.identity(); + mtx = mask.getMatrix(mask._props.matrix).prependMatrix(mtx); + + var ctx = createjs.DisplayObject._hitTestContext; + ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx-x, mtx.ty-y); + + // draw the mask as a solid fill: + mask.graphics.drawAsPath(ctx); + ctx.fillStyle = "#000"; + ctx.fill(); + + if (!this._testHit(ctx)) { return false; } + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, 2, 2); + + return true; + }; + + /** + * @method _getBounds + * @param {Matrix2D} matrix + * @param {Boolean} ignoreTransform If true, does not apply this object's transform. + * @return {Rectangle} + * @protected + **/ + p._getBounds = function(matrix, ignoreTransform) { + var bounds = this.DisplayObject_getBounds(); + if (bounds) { return this._transformBounds(bounds, matrix, ignoreTransform); } + + var mtx = this._props.matrix; + mtx = ignoreTransform ? mtx.identity() : this.getMatrix(mtx); + if (matrix) { mtx.prependMatrix(matrix); } + + var l = this.children.length, rect=null; + for (var i=0; iExample + * This example creates a stage, adds a child to it, then uses {{#crossLink "Ticker"}}{{/crossLink}} to update the child + * and redraw the stage using {{#crossLink "Stage/update"}}{{/crossLink}}. + * + * var stage = new createjs.Stage("canvasElementId"); + * var image = new createjs.Bitmap("imagePath.png"); + * stage.addChild(image); + * createjs.Ticker.addEventListener("tick", handleTick); + * function handleTick(event) { + * image.x += 10; + * stage.update(); + * } + * + * @class Stage + * @extends Container + * @constructor + * @param {HTMLCanvasElement | String | Object} canvas A canvas object that the Stage will render to, or the string id + * of a canvas object in the current document. + **/ + function Stage(canvas) { + this.Container_constructor(); + + + // public properties: + /** + * Indicates whether the stage should automatically clear the canvas before each render. You can set this to false + * to manually control clearing (for generative art, or when pointing multiple stages at the same canvas for + * example). + * + *

    Example

    + * + * var stage = new createjs.Stage("canvasId"); + * stage.autoClear = false; + * + * @property autoClear + * @type Boolean + * @default true + **/ + this.autoClear = true; + + /** + * The canvas the stage will render to. Multiple stages can share a single canvas, but you must disable autoClear for all but the + * first stage that will be ticked (or they will clear each other's render). + * + * When changing the canvas property you must disable the events on the old canvas, and enable events on the + * new canvas or mouse events will not work as expected. For example: + * + * myStage.enableDOMEvents(false); + * myStage.canvas = anotherCanvas; + * myStage.enableDOMEvents(true); + * + * @property canvas + * @type HTMLCanvasElement | Object + **/ + this.canvas = (typeof canvas == "string") ? document.getElementById(canvas) : canvas; + + /** + * The current mouse X position on the canvas. If the mouse leaves the canvas, this will indicate the most recent + * position over the canvas, and mouseInBounds will be set to false. + * @property mouseX + * @type Number + * @readonly + **/ + this.mouseX = 0; + + /** + * The current mouse Y position on the canvas. If the mouse leaves the canvas, this will indicate the most recent + * position over the canvas, and mouseInBounds will be set to false. + * @property mouseY + * @type Number + * @readonly + **/ + this.mouseY = 0; + + /** + * Specifies the area of the stage to affect when calling update. This can be use to selectively + * re-draw specific regions of the canvas. If null, the whole canvas area is drawn. + * @property drawRect + * @type {Rectangle} + */ + this.drawRect = null; + + /** + * Indicates whether display objects should be rendered on whole pixels. You can set the + * {{#crossLink "DisplayObject/snapToPixel"}}{{/crossLink}} property of + * display objects to false to enable/disable this behaviour on a per instance basis. + * @property snapToPixelEnabled + * @type Boolean + * @default false + **/ + this.snapToPixelEnabled = false; + + /** + * Indicates whether the mouse is currently within the bounds of the canvas. + * @property mouseInBounds + * @type Boolean + * @default false + **/ + this.mouseInBounds = false; + + /** + * If true, tick callbacks will be called on all display objects on the stage prior to rendering to the canvas. + * @property tickOnUpdate + * @type Boolean + * @default true + **/ + this.tickOnUpdate = true; + + /** + * If true, mouse move events will continue to be called when the mouse leaves the target canvas. See + * {{#crossLink "Stage/mouseInBounds:property"}}{{/crossLink}}, and {{#crossLink "MouseEvent"}}{{/crossLink}} + * x/y/rawX/rawY. + * @property mouseMoveOutside + * @type Boolean + * @default false + **/ + this.mouseMoveOutside = false; + + + /** + * Prevents selection of other elements in the html page if the user clicks and drags, or double clicks on the canvas. + * This works by calling `preventDefault()` on any mousedown events (or touch equivalent) originating on the canvas. + * @property preventSelection + * @type Boolean + * @default true + **/ + this.preventSelection = true; + + /** + * The hitArea property is not supported for Stage. + * @property hitArea + * @type {DisplayObject} + * @default null + */ + + + // private properties: + /** + * Holds objects with data for each active pointer id. Each object has the following properties: + * x, y, event, target, overTarget, overX, overY, inBounds, posEvtObj (native event that last updated position) + * @property _pointerData + * @type {Object} + * @private + */ + this._pointerData = {}; + + /** + * Number of active pointers. + * @property _pointerCount + * @type {Object} + * @private + */ + this._pointerCount = 0; + + /** + * The ID of the primary pointer. + * @property _primaryPointerID + * @type {Object} + * @private + */ + this._primaryPointerID = null; + + /** + * @property _mouseOverIntervalID + * @protected + * @type Number + **/ + this._mouseOverIntervalID = null; + + /** + * @property _nextStage + * @protected + * @type Stage + **/ + this._nextStage = null; + + /** + * @property _prevStage + * @protected + * @type Stage + **/ + this._prevStage = null; + + + // initialize: + this.enableDOMEvents(true); + } + var p = createjs.extend(Stage, createjs.Container); + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// events: + /** + * Dispatched when the user moves the mouse over the canvas. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event stagemousemove + * @since 0.6.0 + */ + + /** + * Dispatched when the user presses their left mouse button on the canvas. See the {{#crossLink "MouseEvent"}}{{/crossLink}} + * class for a listing of event properties. + * @event stagemousedown + * @since 0.6.0 + */ + + /** + * Dispatched when the user the user presses somewhere on the stage, then releases the mouse button anywhere that the page can detect it (this varies slightly between browsers). + * You can use {{#crossLink "Stage/mouseInBounds:property"}}{{/crossLink}} to check whether the mouse is currently within the stage bounds. + * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. + * @event stagemouseup + * @since 0.6.0 + */ + + /** + * Dispatched when the mouse moves from within the canvas area (mouseInBounds == true) to outside it (mouseInBounds == false). + * This is currently only dispatched for mouse input (not touch). See the {{#crossLink "MouseEvent"}}{{/crossLink}} + * class for a listing of event properties. + * @event mouseleave + * @since 0.7.0 + */ + + /** + * Dispatched when the mouse moves into the canvas area (mouseInBounds == false) from outside it (mouseInBounds == true). + * This is currently only dispatched for mouse input (not touch). See the {{#crossLink "MouseEvent"}}{{/crossLink}} + * class for a listing of event properties. + * @event mouseenter + * @since 0.7.0 + */ + + /** + * Dispatched each update immediately before the tick event is propagated through the display list. + * You can call preventDefault on the event object to cancel propagating the tick event. + * @event tickstart + * @since 0.7.0 + */ + + /** + * Dispatched each update immediately after the tick event is propagated through the display list. Does not fire if + * tickOnUpdate is false. Precedes the "drawstart" event. + * @event tickend + * @since 0.7.0 + */ + + /** + * Dispatched each update immediately before the canvas is cleared and the display list is drawn to it. + * You can call preventDefault on the event object to cancel the draw. + * @event drawstart + * @since 0.7.0 + */ + + /** + * Dispatched each update immediately after the display list is drawn to the canvas and the canvas context is restored. + * @event drawend + * @since 0.7.0 + */ + + +// getter / setters: + /** + * Specifies a target stage that will have mouse / touch interactions relayed to it after this stage handles them. + * This can be useful in cases where you have multiple layered canvases and want user interactions + * events to pass through. For example, this would relay mouse events from topStage to bottomStage: + * + * topStage.nextStage = bottomStage; + * + * To disable relaying, set nextStage to null. + * + * MouseOver, MouseOut, RollOver, and RollOut interactions are also passed through using the mouse over settings + * of the top-most stage, but are only processed if the target stage has mouse over interactions enabled. + * Considerations when using roll over in relay targets:
      + *
    1. The top-most (first) stage must have mouse over interactions enabled (via enableMouseOver)
    2. + *
    3. All stages that wish to participate in mouse over interaction must enable them via enableMouseOver
    4. + *
    5. All relay targets will share the frequency value of the top-most stage
    6. + *
    + * To illustrate, in this example the targetStage would process mouse over interactions at 10hz (despite passing + * 30 as it's desired frequency): + * topStage.nextStage = targetStage; + * topStage.enableMouseOver(10); + * targetStage.enableMouseOver(30); + * + * If the target stage's canvas is completely covered by this stage's canvas, you may also want to disable its + * DOM events using: + * + * targetStage.enableDOMEvents(false); + * + * @property nextStage + * @type {Stage} + **/ + p._get_nextStage = function() { + return this._nextStage; + }; + p._set_nextStage = function(value) { + if (this._nextStage) { this._nextStage._prevStage = null; } + if (value) { value._prevStage = this; } + this._nextStage = value; + }; + + try { + Object.defineProperties(p, { + nextStage: { get: p._get_nextStage, set: p._set_nextStage } + }); + } catch (e) {} // TODO: use Log + + +// public methods: + /** + * Each time the update method is called, the stage will call {{#crossLink "Stage/tick"}}{{/crossLink}} + * unless {{#crossLink "Stage/tickOnUpdate:property"}}{{/crossLink}} is set to false, + * and then render the display list to the canvas. + * + * @method update + * @param {Object} [props] Props object to pass to `tick()`. Should usually be a {{#crossLink "Ticker"}}{{/crossLink}} event object, or similar object with a delta property. + **/ + p.update = function(props) { + if (!this.canvas) { return; } + if (this.tickOnUpdate) { this.tick(props); } + if (this.dispatchEvent("drawstart", false, true) === false) { return; } + createjs.DisplayObject._snapToPixelEnabled = this.snapToPixelEnabled; + var r = this.drawRect, ctx = this.canvas.getContext("2d"); + ctx.setTransform(1, 0, 0, 1, 0, 0); + if (this.autoClear) { + if (r) { ctx.clearRect(r.x, r.y, r.width, r.height); } + else { ctx.clearRect(0, 0, this.canvas.width+1, this.canvas.height+1); } + } + ctx.save(); + if (this.drawRect) { + ctx.beginPath(); + ctx.rect(r.x, r.y, r.width, r.height); + ctx.clip(); + } + this.updateContext(ctx); + this.draw(ctx, false); + ctx.restore(); + this.dispatchEvent("drawend"); + }; + + /** + * Propagates a tick event through the display list. This is automatically called by {{#crossLink "Stage/update"}}{{/crossLink}} + * unless {{#crossLink "Stage/tickOnUpdate:property"}}{{/crossLink}} is set to false. + * + * If a props object is passed to `tick()`, then all of its properties will be copied to the event object that is + * propagated to listeners. + * + * Some time-based features in EaselJS (for example {{#crossLink "Sprite/framerate"}}{{/crossLink}} require that + * a {{#crossLink "Ticker/tick:event"}}{{/crossLink}} event object (or equivalent object with a delta property) be + * passed as the `props` parameter to `tick()`. For example: + * + * Ticker.on("tick", handleTick); + * function handleTick(evtObj) { + * // clone the event object from Ticker, and add some custom data to it: + * var evt = evtObj.clone().set({greeting:"hello", name:"world"}); + * + * // pass it to stage.update(): + * myStage.update(evt); // subsequently calls tick() with the same param + * } + * + * // ... + * myDisplayObject.on("tick", handleDisplayObjectTick); + * function handleDisplayObjectTick(evt) { + * console.log(evt.delta); // the delta property from the Ticker tick event object + * console.log(evt.greeting, evt.name); // custom data: "hello world" + * } + * + * @method tick + * @param {Object} [props] An object with properties that should be copied to the event object. Should usually be a Ticker event object, or similar object with a delta property. + **/ + p.tick = function(props) { + if (!this.tickEnabled || this.dispatchEvent("tickstart", false, true) === false) { return; } + var evtObj = new createjs.Event("tick"); + if (props) { + for (var n in props) { + if (props.hasOwnProperty(n)) { evtObj[n] = props[n]; } + } + } + this._tick(evtObj); + this.dispatchEvent("tickend"); + }; + + /** + * Default event handler that calls the Stage {{#crossLink "Stage/update"}}{{/crossLink}} method when a {{#crossLink "DisplayObject/tick:event"}}{{/crossLink}} + * event is received. This allows you to register a Stage instance as a event listener on {{#crossLink "Ticker"}}{{/crossLink}} + * directly, using: + * + * Ticker.addEventListener("tick", myStage"); + * + * Note that if you subscribe to ticks using this pattern, then the tick event object will be passed through to + * display object tick handlers, instead of delta and paused parameters. + * @property handleEvent + * @type Function + **/ + p.handleEvent = function(evt) { + if (evt.type == "tick") { this.update(evt); } + }; + + /** + * Clears the target canvas. Useful if {{#crossLink "Stage/autoClear:property"}}{{/crossLink}} is set to `false`. + * @method clear + **/ + p.clear = function() { + if (!this.canvas) { return; } + var ctx = this.canvas.getContext("2d"); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, this.canvas.width+1, this.canvas.height+1); + }; + + /** + * Returns a data url that contains a Base64-encoded image of the contents of the stage. The returned data url can + * be specified as the src value of an image element. + * @method toDataURL + * @param {String} [backgroundColor] The background color to be used for the generated image. Any valid CSS color + * value is allowed. The default value is a transparent background. + * @param {String} [mimeType="image/png"] The MIME type of the image format to be create. The default is "image/png". If an unknown MIME type + * is passed in, or if the browser does not support the specified MIME type, the default value will be used. + * @return {String} a Base64 encoded image. + **/ + p.toDataURL = function(backgroundColor, mimeType) { + var data, ctx = this.canvas.getContext('2d'), w = this.canvas.width, h = this.canvas.height; + + if (backgroundColor) { + data = ctx.getImageData(0, 0, w, h); + var compositeOperation = ctx.globalCompositeOperation; + ctx.globalCompositeOperation = "destination-over"; + + ctx.fillStyle = backgroundColor; + ctx.fillRect(0, 0, w, h); + } + + var dataURL = this.canvas.toDataURL(mimeType||"image/png"); + + if(backgroundColor) { + ctx.putImageData(data, 0, 0); + ctx.globalCompositeOperation = compositeOperation; + } + + return dataURL; + }; + + /** + * Enables or disables (by passing a frequency of 0) mouse over ({{#crossLink "DisplayObject/mouseover:event"}}{{/crossLink}} + * and {{#crossLink "DisplayObject/mouseout:event"}}{{/crossLink}}) and roll over events ({{#crossLink "DisplayObject/rollover:event"}}{{/crossLink}} + * and {{#crossLink "DisplayObject/rollout:event"}}{{/crossLink}}) for this stage's display list. These events can + * be expensive to generate, so they are disabled by default. The frequency of the events can be controlled + * independently of mouse move events via the optional `frequency` parameter. + * + *

    Example

    + * + * var stage = new createjs.Stage("canvasId"); + * stage.enableMouseOver(10); // 10 updates per second + * + * @method enableMouseOver + * @param {Number} [frequency=20] Optional param specifying the maximum number of times per second to broadcast + * mouse over/out events. Set to 0 to disable mouse over events completely. Maximum is 50. A lower frequency is less + * responsive, but uses less CPU. + **/ + p.enableMouseOver = function(frequency) { + if (this._mouseOverIntervalID) { + clearInterval(this._mouseOverIntervalID); + this._mouseOverIntervalID = null; + if (frequency == 0) { + this._testMouseOver(true); + } + } + if (frequency == null) { frequency = 20; } + else if (frequency <= 0) { return; } + var o = this; + this._mouseOverIntervalID = setInterval(function(){ o._testMouseOver(); }, 1000/Math.min(50,frequency)); + }; + + /** + * Enables or disables the event listeners that stage adds to DOM elements (window, document and canvas). It is good + * practice to disable events when disposing of a Stage instance, otherwise the stage will continue to receive + * events from the page. + * + * When changing the canvas property you must disable the events on the old canvas, and enable events on the + * new canvas or mouse events will not work as expected. For example: + * + * myStage.enableDOMEvents(false); + * myStage.canvas = anotherCanvas; + * myStage.enableDOMEvents(true); + * + * @method enableDOMEvents + * @param {Boolean} [enable=true] Indicates whether to enable or disable the events. Default is true. + **/ + p.enableDOMEvents = function(enable) { + if (enable == null) { enable = true; } + var n, o, ls = this._eventListeners; + if (!enable && ls) { + for (n in ls) { + o = ls[n]; + o.t.removeEventListener(n, o.f, false); + } + this._eventListeners = null; + } else if (enable && !ls && this.canvas) { + var t = window.addEventListener ? window : document; + var _this = this; + ls = this._eventListeners = {}; + ls["mouseup"] = {t:t, f:function(e) { _this._handleMouseUp(e)} }; + ls["mousemove"] = {t:t, f:function(e) { _this._handleMouseMove(e)} }; + ls["dblclick"] = {t:this.canvas, f:function(e) { _this._handleDoubleClick(e)} }; + ls["mousedown"] = {t:this.canvas, f:function(e) { _this._handleMouseDown(e)} }; + + for (n in ls) { + o = ls[n]; + o.t.addEventListener(n, o.f, false); + } + } + }; + + /** + * Stage instances cannot be cloned. + * @method clone + **/ + p.clone = function() { + throw("Stage cannot be cloned."); + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Stage (name="+ this.name +")]"; + }; + + +// private methods: + /** + * @method _getElementRect + * @protected + * @param {HTMLElement} e + **/ + p._getElementRect = function(e) { + var bounds; + try { bounds = e.getBoundingClientRect(); } // this can fail on disconnected DOM elements in IE9 + catch (err) { bounds = {top: e.offsetTop, left: e.offsetLeft, width:e.offsetWidth, height:e.offsetHeight}; } + + var offX = (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || document.body.clientLeft || 0); + var offY = (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || document.body.clientTop || 0); + + var styles = window.getComputedStyle ? getComputedStyle(e,null) : e.currentStyle; // IE <9 compatibility. + var padL = parseInt(styles.paddingLeft)+parseInt(styles.borderLeftWidth); + var padT = parseInt(styles.paddingTop)+parseInt(styles.borderTopWidth); + var padR = parseInt(styles.paddingRight)+parseInt(styles.borderRightWidth); + var padB = parseInt(styles.paddingBottom)+parseInt(styles.borderBottomWidth); + + // note: in some browsers bounds properties are read only. + return { + left: bounds.left+offX+padL, + right: bounds.right+offX-padR, + top: bounds.top+offY+padT, + bottom: bounds.bottom+offY-padB + } + }; + + /** + * @method _getPointerData + * @protected + * @param {Number} id + **/ + p._getPointerData = function(id) { + var data = this._pointerData[id]; + if (!data) { data = this._pointerData[id] = {x:0,y:0}; } + return data; + }; + + /** + * @method _handleMouseMove + * @protected + * @param {MouseEvent} e + **/ + p._handleMouseMove = function(e) { + if(!e){ e = window.event; } + this._handlePointerMove(-1, e, e.pageX, e.pageY); + }; + + /** + * @method _handlePointerMove + * @protected + * @param {Number} id + * @param {Event} e + * @param {Number} pageX + * @param {Number} pageY + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + **/ + p._handlePointerMove = function(id, e, pageX, pageY, owner) { + if (this._prevStage && owner === undefined) { return; } // redundant listener. + if (!this.canvas) { return; } + var nextStage=this._nextStage, o=this._getPointerData(id); + + var inBounds = o.inBounds; + this._updatePointerPosition(id, e, pageX, pageY); + if (inBounds || o.inBounds || this.mouseMoveOutside) { + if (id === -1 && o.inBounds == !inBounds) { + this._dispatchMouseEvent(this, (inBounds ? "mouseleave" : "mouseenter"), false, id, o, e); + } + + this._dispatchMouseEvent(this, "stagemousemove", false, id, o, e); + this._dispatchMouseEvent(o.target, "pressmove", true, id, o, e); + } + + nextStage&&nextStage._handlePointerMove(id, e, pageX, pageY, null); + }; + + /** + * @method _updatePointerPosition + * @protected + * @param {Number} id + * @param {Event} e + * @param {Number} pageX + * @param {Number} pageY + **/ + p._updatePointerPosition = function(id, e, pageX, pageY) { + var rect = this._getElementRect(this.canvas); + pageX -= rect.left; + pageY -= rect.top; + + var w = this.canvas.width; + var h = this.canvas.height; + pageX /= (rect.right-rect.left)/w; + pageY /= (rect.bottom-rect.top)/h; + var o = this._getPointerData(id); + if (o.inBounds = (pageX >= 0 && pageY >= 0 && pageX <= w-1 && pageY <= h-1)) { + o.x = pageX; + o.y = pageY; + } else if (this.mouseMoveOutside) { + o.x = pageX < 0 ? 0 : (pageX > w-1 ? w-1 : pageX); + o.y = pageY < 0 ? 0 : (pageY > h-1 ? h-1 : pageY); + } + + o.posEvtObj = e; + o.rawX = pageX; + o.rawY = pageY; + + if (id === this._primaryPointerID || id === -1) { + this.mouseX = o.x; + this.mouseY = o.y; + this.mouseInBounds = o.inBounds; + } + }; + + /** + * @method _handleMouseUp + * @protected + * @param {MouseEvent} e + **/ + p._handleMouseUp = function(e) { + this._handlePointerUp(-1, e, false); + }; + + /** + * @method _handlePointerUp + * @protected + * @param {Number} id + * @param {Event} e + * @param {Boolean} clear + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + **/ + p._handlePointerUp = function(id, e, clear, owner) { + var nextStage = this._nextStage, o = this._getPointerData(id); + if (this._prevStage && owner === undefined) { return; } // redundant listener. + + var target=null, oTarget = o.target; + if (!owner && (oTarget || nextStage)) { target = this._getObjectsUnderPoint(o.x, o.y, null, true); } + + if (o.down) { this._dispatchMouseEvent(this, "stagemouseup", false, id, o, e, target); o.down = false; } + + if (target == oTarget) { this._dispatchMouseEvent(oTarget, "click", true, id, o, e); } + this._dispatchMouseEvent(oTarget, "pressup", true, id, o, e); + + if (clear) { + if (id==this._primaryPointerID) { this._primaryPointerID = null; } + delete(this._pointerData[id]); + } else { o.target = null; } + + nextStage&&nextStage._handlePointerUp(id, e, clear, owner || target && this); + }; + + /** + * @method _handleMouseDown + * @protected + * @param {MouseEvent} e + **/ + p._handleMouseDown = function(e) { + this._handlePointerDown(-1, e, e.pageX, e.pageY); + }; + + /** + * @method _handlePointerDown + * @protected + * @param {Number} id + * @param {Event} e + * @param {Number} pageX + * @param {Number} pageY + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + **/ + p._handlePointerDown = function(id, e, pageX, pageY, owner) { + if (this.preventSelection) { e.preventDefault(); } + if (this._primaryPointerID == null || id === -1) { this._primaryPointerID = id; } // mouse always takes over. + + if (pageY != null) { this._updatePointerPosition(id, e, pageX, pageY); } + var target = null, nextStage = this._nextStage, o = this._getPointerData(id); + if (!owner) { target = o.target = this._getObjectsUnderPoint(o.x, o.y, null, true); } + + if (o.inBounds) { this._dispatchMouseEvent(this, "stagemousedown", false, id, o, e, target); o.down = true; } + this._dispatchMouseEvent(target, "mousedown", true, id, o, e); + + nextStage&&nextStage._handlePointerDown(id, e, pageX, pageY, owner || target && this); + }; + + /** + * @method _testMouseOver + * @param {Boolean} clear If true, clears the mouseover / rollover (ie. no target) + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + * @param {Stage} eventTarget The stage that the cursor is actively over. + * @protected + **/ + p._testMouseOver = function(clear, owner, eventTarget) { + if (this._prevStage && owner === undefined) { return; } // redundant listener. + + var nextStage = this._nextStage; + if (!this._mouseOverIntervalID) { + // not enabled for mouseover, but should still relay the event. + nextStage&&nextStage._testMouseOver(clear, owner, eventTarget); + return; + } + var o = this._getPointerData(-1); + // only update if the mouse position has changed. This provides a lot of optimization, but has some trade-offs. + if (!o || (!clear && this.mouseX == this._mouseOverX && this.mouseY == this._mouseOverY && this.mouseInBounds)) { return; } + + var e = o.posEvtObj; + var isEventTarget = eventTarget || e&&(e.target == this.canvas); + var target=null, common = -1, cursor="", t, i, l; + + if (!owner && (clear || this.mouseInBounds && isEventTarget)) { + target = this._getObjectsUnderPoint(this.mouseX, this.mouseY, null, true); + this._mouseOverX = this.mouseX; + this._mouseOverY = this.mouseY; + } + + var oldList = this._mouseOverTarget||[]; + var oldTarget = oldList[oldList.length-1]; + var list = this._mouseOverTarget = []; + + // generate ancestor list and check for cursor: + t = target; + while (t) { + list.unshift(t); + if (!cursor) { cursor = t.cursor; } + t = t.parent; + } + this.canvas.style.cursor = cursor; + if (!owner && eventTarget) { eventTarget.canvas.style.cursor = cursor; } + + // find common ancestor: + for (i=0,l=list.length; icommon; i--) { + this._dispatchMouseEvent(oldList[i], "rollout", false, -1, o, e, target); + } + + for (i=list.length-1; i>common; i--) { + this._dispatchMouseEvent(list[i], "rollover", false, -1, o, e, oldTarget); + } + + if (oldTarget != target) { + this._dispatchMouseEvent(target, "mouseover", true, -1, o, e, oldTarget); + } + + nextStage&&nextStage._testMouseOver(clear, owner || target && this, eventTarget || isEventTarget && this); + }; + + /** + * @method _handleDoubleClick + * @protected + * @param {MouseEvent} e + * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. + **/ + p._handleDoubleClick = function(e, owner) { + var target=null, nextStage=this._nextStage, o=this._getPointerData(-1); + if (!owner) { + target = this._getObjectsUnderPoint(o.x, o.y, null, true); + this._dispatchMouseEvent(target, "dblclick", true, -1, o, e); + } + nextStage&&nextStage._handleDoubleClick(e, owner || target && this); + }; + + /** + * @method _dispatchMouseEvent + * @protected + * @param {DisplayObject} target + * @param {String} type + * @param {Boolean} bubbles + * @param {Number} pointerId + * @param {Object} o + * @param {MouseEvent} [nativeEvent] + * @param {DisplayObject} [relatedTarget] + **/ + p._dispatchMouseEvent = function(target, type, bubbles, pointerId, o, nativeEvent, relatedTarget) { + // TODO: might be worth either reusing MouseEvent instances, or adding a willTrigger method to avoid GC. + if (!target || (!bubbles && !target.hasEventListener(type))) { return; } + /* + // TODO: account for stage transformations? + this._mtx = this.getConcatenatedMatrix(this._mtx).invert(); + var pt = this._mtx.transformPoint(o.x, o.y); + var evt = new createjs.MouseEvent(type, bubbles, false, pt.x, pt.y, nativeEvent, pointerId, pointerId==this._primaryPointerID || pointerId==-1, o.rawX, o.rawY); + */ + var evt = new createjs.MouseEvent(type, bubbles, false, o.x, o.y, nativeEvent, pointerId, pointerId === this._primaryPointerID || pointerId === -1, o.rawX, o.rawY, relatedTarget); + target.dispatchEvent(evt); + }; + + + createjs.Stage = createjs.promote(Stage, "Container"); }()); //############################################################################## -// DisplayObject.js +// Bitmap.js //############################################################################## this.createjs = this.createjs||{}; (function() { - "use strict"; - - -// constructor: + /** - * DisplayObject is an abstract class that should not be constructed directly. Instead construct subclasses such as - * {{#crossLink "Container"}}{{/crossLink}}, {{#crossLink "Bitmap"}}{{/crossLink}}, and {{#crossLink "Shape"}}{{/crossLink}}. - * DisplayObject is the base class for all display classes in the EaselJS library. It defines the core properties and - * methods that are shared between all display objects, such as transformation properties (x, y, scaleX, scaleY, etc), - * caching, and mouse handlers. - * @class DisplayObject - * @extends EventDispatcher + * A Bitmap represents an Image, Canvas, or Video in the display list. A Bitmap can be instantiated using an existing + * HTML element, or a string. + * + *

    Example

    + * + * var bitmap = new createjs.Bitmap("imagePath.jpg"); + * + * Notes: + *
      + *
    1. When a string path or image tag that is not yet loaded is used, the stage may need to be redrawn before it + * will be displayed.
    2. + *
    3. Bitmaps with an SVG source currently will not respect an alpha value other than 0 or 1. To get around this, + * the Bitmap can be cached.
    4. + *
    5. Bitmaps with an SVG source will taint the canvas with cross-origin data, which prevents interactivity. This + * happens in all browsers except recent Firefox builds.
    6. + *
    7. Images loaded cross-origin will throw cross-origin security errors when interacted with using a mouse, using + * methods such as `getObjectUnderPoint`, or using filters, or caching. You can get around this by setting + * `crossOrigin` flags on your images before passing them to EaselJS, eg: `img.crossOrigin="Anonymous";`
    8. + *
    + * + * @class Bitmap + * @extends DisplayObject * @constructor + * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | String} imageOrUri The source object or URI to an image to + * display. This can be either an Image, Canvas, or Video object, or a string URI to an image file to load and use. + * If it is a URI, a new Image object will be constructed and assigned to the .image property. **/ - function DisplayObject() { - this.EventDispatcher_constructor(); + function Bitmap(imageOrUri) { + this.DisplayObject_constructor(); // public properties: /** - * The alpha (transparency) for this display object. 0 is fully transparent, 1 is fully opaque. - * @property alpha - * @type {Number} - * @default 1 - **/ - this.alpha = 1; - - /** - * If a cache is active, this returns the canvas that holds the cached version of this display object. See {{#crossLink "cache"}}{{/crossLink}} - * for more information. - * @property cacheCanvas - * @type {HTMLCanvasElement | Object} - * @default null - * @readonly - **/ - this.cacheCanvas = null; - - /** - * Returns an ID number that uniquely identifies the current cache for this display object. This can be used to - * determine if the cache has changed since a previous check. - * @property cacheID - * @type {Number} - * @default 0 - */ - this.cacheID = 0; - - /** - * Unique ID for this display object. Makes display objects easier for some uses. - * @property id - * @type {Number} - * @default -1 - **/ - this.id = createjs.UID.get(); - - /** - * Indicates whether to include this object when running mouse interactions. Setting this to `false` for children - * of a {{#crossLink "Container"}}{{/crossLink}} will cause events on the Container to not fire when that child is - * clicked. Setting this property to `false` does not prevent the {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}} - * method from returning the child. - * - * Note: In EaselJS 0.7.0, the mouseEnabled property will not work properly with nested Containers. Please - * check out the latest NEXT version in GitHub for an updated version with this issue resolved. The fix will be - * provided in the next release of EaselJS. - * @property mouseEnabled - * @type {Boolean} - * @default true - **/ - this.mouseEnabled = true; - - /** - * If false, the tick will not run on this display object (or its children). This can provide some performance benefits. - * In addition to preventing the "tick" event from being dispatched, it will also prevent tick related updates - * on some display objects (ex. Sprite & MovieClip frame advancing, DOMElement visibility handling). - * @property tickEnabled - * @type Boolean - * @default true - **/ - this.tickEnabled = true; - - /** - * An optional name for this display object. Included in {{#crossLink "DisplayObject/toString"}}{{/crossLink}} . Useful for - * debugging. - * @property name - * @type {String} - * @default null - **/ - this.name = null; - - /** - * A reference to the {{#crossLink "Container"}}{{/crossLink}} or {{#crossLink "Stage"}}{{/crossLink}} object that - * contains this display object, or null if it has not been added - * to one. - * @property parent - * @final - * @type {Container} - * @default null - * @readonly - **/ - this.parent = null; - - /** - * The left offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate - * around its center, you would set regX and {{#crossLink "DisplayObject/regY:property"}}{{/crossLink}} to 50. - * @property regX - * @type {Number} - * @default 0 - **/ - this.regX = 0; - - /** - * The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around - * its center, you would set {{#crossLink "DisplayObject/regX:property"}}{{/crossLink}} and regY to 50. - * @property regY - * @type {Number} - * @default 0 - **/ - this.regY = 0; - - /** - * The rotation in degrees for this display object. - * @property rotation - * @type {Number} - * @default 0 - **/ - this.rotation = 0; - - /** - * The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display - * object to twice its nominal width. To horizontally flip an object, set the scale to a negative number. - * @property scaleX - * @type {Number} - * @default 1 + * The image to render. This can be an Image, a Canvas, or a Video. Not all browsers (especially + * mobile browsers) support drawing video to a canvas. + * @property image + * @type HTMLImageElement | HTMLCanvasElement | HTMLVideoElement **/ - this.scaleX = 1; + if (typeof imageOrUri == "string") { + this.image = document.createElement("img"); + this.image.src = imageOrUri; + } else { + this.image = imageOrUri; + } /** - * The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display - * object to half its nominal height. To vertically flip an object, set the scale to a negative number. - * @property scaleY - * @type {Number} - * @default 1 - **/ - this.scaleY = 1; + * Specifies an area of the source image to draw. If omitted, the whole image will be drawn. + * Note that video sources must have a width / height set to work correctly with `sourceRect`. + * @property sourceRect + * @type Rectangle + * @default null + */ + this.sourceRect = null; + } + var p = createjs.extend(Bitmap, createjs.DisplayObject); - /** - * The factor to skew this display object horizontally. - * @property skewX - * @type {Number} - * @default 0 - **/ - this.skewX = 0; - /** - * The factor to skew this display object vertically. - * @property skewY - * @type {Number} - * @default 0 - **/ - this.skewY = 0; +// public methods: + /** + * Constructor alias for backwards compatibility. This method will be removed in future versions. + * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. + * @method initialize + * @deprecated in favour of `createjs.promote()` + **/ + p.initialize = Bitmap; // TODO: deprecated. + + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var image = this.image; + var hasContent = this.cacheCanvas || (image && (image.naturalWidth || image.getContext || image.readyState >= 2)); + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + * @return {Boolean} + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache) || !this.image) { return true; } + var img = this.image, rect = this.sourceRect; + if (rect) { + // some browsers choke on out of bound values, so we'll fix them: + var x1 = rect.x, y1 = rect.y, x2 = x1 + rect.width, y2 = y1 + rect.height, x = 0, y = 0, w = img.width, h = img.height; + if (x1 < 0) { x -= x1; x1 = 0; } + if (x2 > w) { x2 = w; } + if (y1 < 0) { y -= y1; y1 = 0; } + if (y2 > h) { y2 = h; } + ctx.drawImage(img, x1, y1, x2-x1, y2-y1, x, y, x2-x1, y2-y1); + } else { + ctx.drawImage(img, 0, 0); + } + return true; + }; - /** - * A shadow object that defines the shadow to render on this display object. Set to `null` to remove a shadow. If - * null, this property is inherited from the parent container. - * @property shadow - * @type {Shadow} - * @default null - **/ - this.shadow = null; + //Note, the doc sections below document using the specified APIs (from DisplayObject) from + //Bitmap. This is why they have no method implementations. - /** - * Indicates whether this display object should be rendered to the canvas and included when running the Stage - * {{#crossLink "Stage/getObjectsUnderPoint"}}{{/crossLink}} method. - * @property visible - * @type {Boolean} - * @default true - **/ - this.visible = true; + /** + * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. + * You should not cache Bitmap instances as it can degrade performance. + * + * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. + * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} + * method. + * @method cache + **/ + + /** + * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. + * You should not cache Bitmap instances as it can degrade performance. + * + * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. + * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} + * method. + * @method updateCache + **/ + + /** + * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. + * You should not cache Bitmap instances as it can degrade performance. + * + * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. + * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} + * method. + * @method uncache + **/ + + /** + * Docced in superclass. + */ + p.getBounds = function() { + var rect = this.DisplayObject_getBounds(); + if (rect) { return rect; } + var image = this.image, o = this.sourceRect || image; + var hasContent = (image && (image.naturalWidth || image.getContext || image.readyState >= 2)); + return hasContent ? this._rectangle.setValues(0, 0, o.width, o.height) : null; + }; + + /** + * Returns a clone of the Bitmap instance. + * @method clone + * @return {Bitmap} a clone of the Bitmap instance. + **/ + p.clone = function() { + var o = new Bitmap(this.image); + if (this.sourceRect) { o.sourceRect = this.sourceRect.clone(); } + this._cloneProps(o); + return o; + }; + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Bitmap (name="+ this.name +")]"; + }; + + + createjs.Bitmap = createjs.promote(Bitmap, "DisplayObject"); +}()); + +//############################################################################## +// Sprite.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Displays a frame or sequence of frames (ie. an animation) from a SpriteSheet instance. A sprite sheet is a series of + * images (usually animation frames) combined into a single image. For example, an animation consisting of 8 100x100 + * images could be combined into a 400x200 sprite sheet (4 frames across by 2 high). You can display individual frames, + * play frames as an animation, and even sequence animations together. + * + * See the {{#crossLink "SpriteSheet"}}{{/crossLink}} class for more information on setting up frames and animations. + * + *

    Example

    + * + * var instance = new createjs.Sprite(spriteSheet); + * instance.gotoAndStop("frameName"); + * + * Until {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} or {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} is called, + * only the first defined frame defined in the sprite sheet will be displayed. + * + * @class Sprite + * @extends DisplayObject + * @constructor + * @param {SpriteSheet} spriteSheet The SpriteSheet instance to play back. This includes the source image(s), frame + * dimensions, and frame data. See {{#crossLink "SpriteSheet"}}{{/crossLink}} for more information. + * @param {String|Number} [frameOrAnimation] The frame number or animation to play initially. + **/ + function Sprite(spriteSheet, frameOrAnimation) { + this.DisplayObject_constructor(); + + + // public properties: /** - * The x (horizontal) position of the display object, relative to its parent. - * @property x + * The frame index that will be drawn when draw is called. Note that with some {{#crossLink "SpriteSheet"}}{{/crossLink}} + * definitions, this will advance non-sequentially. This will always be an integer value. + * @property currentFrame * @type {Number} * @default 0 + * @readonly **/ - this.x = 0; + this.currentFrame = 0; - /** The y (vertical) position of the display object, relative to its parent. - * @property y - * @type {Number} - * @default 0 - **/ - this.y = 0; - - /** - * If set, defines the transformation for this display object, overriding all other transformation properties - * (x, y, rotation, scale, skew). - * @property transformMatrix - * @type {Matrix2D} - * @default null - **/ - this.transformMatrix = null; - /** - * The composite operation indicates how the pixels of this display object will be composited with the elements - * behind it. If `null`, this property is inherited from the parent container. For more information, read the - * - * whatwg spec on compositing. - * @property compositeOperation + * Returns the name of the currently playing animation. + * @property currentAnimation * @type {String} - * @default null + * @final + * @readonly **/ - this.compositeOperation = null; + this.currentAnimation = null; /** - * Indicates whether the display object should be drawn to a whole pixel when - * {{#crossLink "Stage/snapToPixelEnabled"}}{{/crossLink}} is true. To enable/disable snapping on whole - * categories of display objects, set this value on the prototype (Ex. Text.prototype.snapToPixel = true). - * @property snapToPixel + * Prevents the animation from advancing each tick automatically. For example, you could create a sprite + * sheet of icons, set paused to true, and display the appropriate icon by setting currentFrame. + * @property paused * @type {Boolean} - * @default true + * @default false **/ - this.snapToPixel = true; + this.paused = true; /** - * An array of Filter objects to apply to this display object. Filters are only applied / updated when {{#crossLink "cache"}}{{/crossLink}} - * or {{#crossLink "updateCache"}}{{/crossLink}} is called on the display object, and only apply to the area that is - * cached. - * @property filters - * @type {Array} - * @default null + * The SpriteSheet instance to play back. This includes the source image, frame dimensions, and frame + * data. See {{#crossLink "SpriteSheet"}}{{/crossLink}} for more information. + * @property spriteSheet + * @type {SpriteSheet} + * @readonly **/ - this.filters = null; - - /** - * A Shape instance that defines a vector mask (clipping path) for this display object. The shape's transformation - * will be applied relative to the display object's parent coordinates (as if it were a child of the parent). - * @property mask - * @type {Shape} - * @default null - */ - this.mask = null; - - /** - * A display object that will be tested when checking mouse interactions or testing {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}}. - * The hit area will have its transformation applied relative to this display object's coordinate space (as though - * the hit test object were a child of this display object and relative to its regX/Y). The hitArea will be tested - * using only its own `alpha` value regardless of the alpha value on the target display object, or the target's - * ancestors (parents). - * - * If set on a {{#crossLink "Container"}}{{/crossLink}}, children of the Container will not receive mouse events. - * This is similar to setting {{#crossLink "mouseChildren"}}{{/crossLink}} to false. - * - * Note that hitArea is NOT currently used by the `hitTest()` method, nor is it supported for {{#crossLink "Stage"}}{{/crossLink}}. - * @property hitArea - * @type {DisplayObject} - * @default null - */ - this.hitArea = null; - - /** - * A CSS cursor (ex. "pointer", "help", "text", etc) that will be displayed when the user hovers over this display - * object. You must enable mouseover events using the {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}} method to - * use this property. Setting a non-null cursor on a Container will override the cursor set on its descendants. - * @property cursor - * @type {String} - * @default null - */ - this.cursor = null; + this.spriteSheet = spriteSheet; - - // private properties: /** - * @property _cacheOffsetX - * @protected + * Specifies the current frame index within the currently playing animation. When playing normally, this will increase + * from 0 to n-1, where n is the number of frames in the current animation. + * + * This could be a non-integer value if + * using time-based playback (see {{#crossLink "Sprite/framerate"}}{{/crossLink}}, or if the animation's speed is + * not an integer. + * @property currentAnimationFrame * @type {Number} * @default 0 **/ - this._cacheOffsetX = 0; + this.currentAnimationFrame = 0; /** - * @property _cacheOffsetY - * @protected - * @type {Number} - * @default 0 - **/ - this._cacheOffsetY = 0; - - /** - * @property _filterOffsetX - * @protected - * @type {Number} - * @default 0 - **/ - this._filterOffsetX = 0; - - /** - * @property _filterOffsetY - * @protected - * @type {Number} - * @default 0 - **/ - this._filterOffsetY = 0; - - /** - * @property _cacheScale - * @protected + * By default Sprite instances advance one frame per tick. Specifying a framerate for the Sprite (or its related + * SpriteSheet) will cause it to advance based on elapsed time between ticks as appropriate to maintain the target + * framerate. + * + * For example, if a Sprite with a framerate of 10 is placed on a Stage being updated at 40fps, then the Sprite will + * advance roughly one frame every 4 ticks. This will not be exact, because the time between each tick will + * vary slightly between frames. + * + * This feature is dependent on the tick event object (or an object with an appropriate "delta" property) being + * passed into {{#crossLink "Stage/update"}}{{/crossLink}}. + * @property framerate * @type {Number} - * @default 1 + * @default 0 **/ - this._cacheScale = 1; + this.framerate = 0; - /** - * @property _cacheDataURLID - * @protected - * @type {Number} - * @default 0 - */ - this._cacheDataURLID = 0; - - /** - * @property _cacheDataURL - * @protected - * @type {String} - * @default null - */ - this._cacheDataURL = null; + // private properties: /** - * @property _props + * Current animation object. + * @property _animation * @protected - * @type {DisplayObject} + * @type {Object} * @default null **/ - this._props = new createjs.DisplayProps(); + this._animation = null; /** - * @property _rectangle + * Current frame index. + * @property _currentFrame * @protected - * @type {Rectangle} + * @type {Number} * @default null **/ - this._rectangle = new createjs.Rectangle(); - + this._currentFrame = null; + /** - * @property _bounds + * Skips the next auto advance. Used by gotoAndPlay to avoid immediately jumping to the next frame + * @property _skipAdvance * @protected - * @type {Rectangle} - * @default null + * @type {Boolean} + * @default false **/ - this._bounds = null; - } - var p = createjs.extend(DisplayObject, createjs.EventDispatcher); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - -// static properties: - /** - * Listing of mouse event names. Used in _hasMouseEventListener. - * @property _MOUSE_EVENTS - * @protected - * @static - * @type {Array} - **/ - DisplayObject._MOUSE_EVENTS = ["click","dblclick","mousedown","mouseout","mouseover","pressmove","pressup","rollout","rollover"]; - - /** - * Suppresses errors generated when using features like hitTest, mouse events, and {{#crossLink "getObjectsUnderPoint"}}{{/crossLink}} - * with cross domain content. - * @property suppressCrossDomainErrors - * @static - * @type {Boolean} - * @default false - **/ - DisplayObject.suppressCrossDomainErrors = false; - - /** - * @property _snapToPixelEnabled - * @protected - * @static - * @type {Boolean} - * @default false - **/ - DisplayObject._snapToPixelEnabled = false; // stage.snapToPixelEnabled is temporarily copied here during a draw to provide global access. - - /** - * @property _hitTestCanvas - * @type {HTMLCanvasElement | Object} - * @static - * @protected - **/ - /** - * @property _hitTestContext - * @type {CanvasRenderingContext2D} - * @static - * @protected - **/ - var canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); // prevent errors on load in browsers without canvas. - if (canvas.getContext) { - DisplayObject._hitTestCanvas = canvas; - DisplayObject._hitTestContext = canvas.getContext("2d"); - canvas.width = canvas.height = 1; + this._skipAdvance = false; + + + if (frameOrAnimation != null) { this.gotoAndPlay(frameOrAnimation); } } + var p = createjs.extend(Sprite, createjs.DisplayObject); /** - * @property _nextCacheID - * @type {Number} - * @static - * @protected + * Constructor alias for backwards compatibility. This method will be removed in future versions. + * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. + * @method initialize + * @deprecated in favour of `createjs.promote()` **/ - DisplayObject._nextCacheID = 1; + p.initialize = Sprite; // TODO: Deprecated. This is for backwards support of FlashCC spritesheet export. // events: /** - * Dispatched when the user presses their left mouse button over the display object. See the - * {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event mousedown - * @since 0.6.0 - */ - - /** - * Dispatched when the user presses their left mouse button and then releases it while over the display object. - * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event click - * @since 0.6.0 - */ - - /** - * Dispatched when the user double clicks their left mouse button over this display object. - * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event dblclick + * Dispatched when an animation reaches its ends. + * @event animationend + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @param {String} name The name of the animation that just ended. + * @param {String} next The name of the next animation that will be played, or null. This will be the same as name if the animation is looping. * @since 0.6.0 */ /** - * Dispatched when the user's mouse enters this display object. This event must be enabled using - * {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. See also {{#crossLink "DisplayObject/rollover:event"}}{{/crossLink}}. - * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event mouseover - * @since 0.6.0 + * Dispatched any time the current frame changes. For example, this could be due to automatic advancement on a tick, + * or calling gotoAndPlay() or gotoAndStop(). + * @event change + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. */ + +// public methods: /** - * Dispatched when the user's mouse leaves this display object. This event must be enabled using - * {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. See also {{#crossLink "DisplayObject/rollout:event"}}{{/crossLink}}. - * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event mouseout - * @since 0.6.0 - */ - - /** - * This event is similar to {{#crossLink "DisplayObject/mouseover:event"}}{{/crossLink}}, with the following - * differences: it does not bubble, and it considers {{#crossLink "Container"}}{{/crossLink}} instances as an - * aggregate of their content. - * - * For example, myContainer contains two overlapping children: shapeA and shapeB. The user moves their mouse over - * shapeA and then directly on to shapeB. With a listener for {{#crossLink "mouseover:event"}}{{/crossLink}} on - * myContainer, two events would be received, each targeting a child element:
      - *
    1. when the mouse enters shapeA (target=shapeA)
    2. - *
    3. when the mouse enters shapeB (target=shapeB)
    4. - *
    - * However, with a listener for "rollover" instead, only a single event is received when the mouse first enters - * the aggregate myContainer content (target=myContainer). - * - * This event must be enabled using {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. - * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event rollover - * @since 0.7.0 - */ - - /** - * This event is similar to {{#crossLink "DisplayObject/mouseout:event"}}{{/crossLink}}, with the following - * differences: it does not bubble, and it considers {{#crossLink "Container"}}{{/crossLink}} instances as an - * aggregate of their content. - * - * For example, myContainer contains two overlapping children: shapeA and shapeB. The user moves their mouse over - * shapeA, then directly on to shapeB, then off both. With a listener for {{#crossLink "mouseout:event"}}{{/crossLink}} - * on myContainer, two events would be received, each targeting a child element:
      - *
    1. when the mouse leaves shapeA (target=shapeA)
    2. - *
    3. when the mouse leaves shapeB (target=shapeB)
    4. - *
    - * However, with a listener for "rollout" instead, only a single event is received when the mouse leaves - * the aggregate myContainer content (target=myContainer). - * - * This event must be enabled using {{#crossLink "Stage/enableMouseOver"}}{{/crossLink}}. - * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event rollout - * @since 0.7.0 - */ - - /** - * After a {{#crossLink "DisplayObject/mousedown:event"}}{{/crossLink}} occurs on a display object, a pressmove - * event will be generated on that object whenever the mouse moves until the mouse press is released. This can be - * useful for dragging and similar operations. - * @event pressmove - * @since 0.7.0 - */ - - /** - * After a {{#crossLink "DisplayObject/mousedown:event"}}{{/crossLink}} occurs on a display object, a pressup event - * will be generated on that object when that mouse press is released. This can be useful for dragging and similar - * operations. - * @event pressup - * @since 0.7.0 - */ - + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var hasContent = this.cacheCanvas || this.spriteSheet.complete; + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + }; + /** - * Dispatched when the display object is added to a parent container. - * @event added - */ - + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + this._normalizeFrame(); + var o = this.spriteSheet.getFrame(this._currentFrame|0); + if (!o) { return false; } + var rect = o.rect; + if (rect.width && rect.height) { ctx.drawImage(o.image, rect.x, rect.y, rect.width, rect.height, -o.regX, -o.regY, rect.width, rect.height); } + return true; + }; + + //Note, the doc sections below document using the specified APIs (from DisplayObject) from + //Bitmap. This is why they have no method implementations. + /** - * Dispatched when the display object is removed from its parent container. - * @event removed - */ - + * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. + * You should not cache Sprite instances as it can degrade performance. + * @method cache + **/ + /** - * Dispatched on each display object on a stage whenever the stage updates. This occurs immediately before the - * rendering (draw) pass. When {{#crossLink "Stage/update"}}{{/crossLink}} is called, first all display objects on - * the stage dispatch the tick event, then all of the display objects are drawn to stage. Children will have their - * {{#crossLink "tick:event"}}{{/crossLink}} event dispatched in order of their depth prior to the event being - * dispatched on their parent. - * @event tick - * @param {Object} target The object that dispatched the event. - * @param {String} type The event type. - * @param {Array} params An array containing any arguments that were passed to the Stage.update() method. For - * example if you called stage.update("hello"), then the params would be ["hello"]. - * @since 0.6.0 - */ - - -// getter / setters: + * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. + * You should not cache Sprite instances as it can degrade performance. + * @method updateCache + **/ + /** - * Use the {{#crossLink "DisplayObject/stage:property"}}{{/crossLink}} property instead. - * @method getStage - * @return {Stage} - * @deprecated + * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. + * You should not cache Sprite instances as it can degrade performance. + * @method uncache **/ - p.getStage = function() { - // uses dynamic access to avoid circular dependencies; - var o = this, _Stage = createjs["Stage"]; - while (o.parent) { o = o.parent; } - if (o instanceof _Stage) { return o; } - return null; + + /** + * Play (unpause) the current animation. The Sprite will be paused if either {{#crossLink "Sprite/stop"}}{{/crossLink}} + * or {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} is called. Single frame animations will remain + * unchanged. + * @method play + **/ + p.play = function() { + this.paused = false; }; /** - * Returns the Stage instance that this display object will be rendered on, or null if it has not been added to one. - * @property stage - * @type {Stage} - * @readonly + * Stop playing a running animation. The Sprite will be playing if {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} + * is called. Note that calling {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} or {{#crossLink "Sprite/play"}}{{/crossLink}} + * will resume playback. + * @method stop **/ - try { - Object.defineProperties(p, { - stage: { get: p.getStage } - }); - } catch (e) {} + p.stop = function() { + this.paused = true; + }; + /** + * Sets paused to false and plays the specified animation name, named frame, or frame number. + * @method gotoAndPlay + * @param {String|Number} frameOrAnimation The frame number or animation name that the playhead should move to + * and begin playing. + **/ + p.gotoAndPlay = function(frameOrAnimation) { + this.paused = false; + this._skipAdvance = true; + this._goto(frameOrAnimation); + }; -// public methods: /** - * Returns true or false indicating whether the display object would be visible if drawn to a canvas. - * This does not account for whether it would be visible within the boundaries of the stage. - * - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method isVisible - * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + * Sets paused to true and seeks to the specified animation name, named frame, or frame number. + * @method gotoAndStop + * @param {String|Number} frameOrAnimation The frame number or animation name that the playhead should move to + * and stop. **/ - p.isVisible = function() { - return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0); + p.gotoAndStop = function(frameOrAnimation) { + this.paused = true; + this._goto(frameOrAnimation); }; /** - * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. - * Returns true if the draw was handled (useful for overriding functionality). + * Advances the playhead. This occurs automatically each tick by default. + * @param [time] {Number} The amount of time in ms to advance by. Only applicable if framerate is set on the Sprite + * or its SpriteSheet. + * @method advance + */ + p.advance = function(time) { + var fps = this.framerate || this.spriteSheet.framerate; + var t = (fps && time != null) ? time/(1000/fps) : 1; + this._normalizeFrame(t); + }; + + /** + * Returns a {{#crossLink "Rectangle"}}{{/crossLink}} instance defining the bounds of the current frame relative to + * the origin. For example, a 90 x 70 frame with regX=50 and regY=40 would return a + * rectangle with [x=-50, y=-40, width=90, height=70]. This ignores transformations on the display object. * - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method draw - * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. For example, - * used for drawing the cache (to prevent it from simply drawing an existing cache back into itself). - * @return {Boolean} + * Also see the SpriteSheet {{#crossLink "SpriteSheet/getFrameBounds"}}{{/crossLink}} method. + * @method getBounds + * @return {Rectangle} A Rectangle instance. Returns null if the frame does not exist, or the image is not fully + * loaded. **/ - p.draw = function(ctx, ignoreCache) { - var cacheCanvas = this.cacheCanvas; - if (ignoreCache || !cacheCanvas) { return false; } - var scale = this._cacheScale; - ctx.drawImage(cacheCanvas, this._cacheOffsetX+this._filterOffsetX, this._cacheOffsetY+this._filterOffsetY, cacheCanvas.width/scale, cacheCanvas.height/scale); - return true; + p.getBounds = function() { + // TODO: should this normalizeFrame? + return this.DisplayObject_getBounds() || this.spriteSheet.getFrameBounds(this.currentFrame, this._rectangle); }; - + /** - * Applies this display object's transformation, alpha, globalCompositeOperation, clipping path (mask), and shadow - * to the specified context. This is typically called prior to {{#crossLink "DisplayObject/draw"}}{{/crossLink}}. - * @method updateContext - * @param {CanvasRenderingContext2D} ctx The canvas 2D to update. + * Returns a clone of the Sprite instance. Note that the same SpriteSheet is shared between cloned + * instances. + * @method clone + * @return {Sprite} a clone of the Sprite instance. **/ - p.updateContext = function(ctx) { - var o=this, mask=o.mask, mtx= o._props.matrix; - - if (mask && mask.graphics && !mask.graphics.isEmpty()) { - mask.getMatrix(mtx); - ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty); - - mask.graphics.drawAsPath(ctx); - ctx.clip(); - - mtx.invert(); - ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty); - } - - this.getMatrix(mtx); - var tx = mtx.tx, ty = mtx.ty; - if (DisplayObject._snapToPixelEnabled && o.snapToPixel) { - tx = tx + (tx < 0 ? -0.5 : 0.5) | 0; - ty = ty + (ty < 0 ? -0.5 : 0.5) | 0; - } - ctx.transform(mtx.a, mtx.b, mtx.c, mtx.d, tx, ty); - ctx.globalAlpha *= o.alpha; - if (o.compositeOperation) { ctx.globalCompositeOperation = o.compositeOperation; } - if (o.shadow) { this._applyShadow(ctx, o.shadow); } + p.clone = function() { + return this._cloneProps(new Sprite(this.spriteSheet)); }; /** - * Draws the display object into a new canvas, which is then used for subsequent draws. For complex content - * that does not change frequently (ex. a Container with many children that do not move, or a complex vector Shape), - * this can provide for much faster rendering because the content does not need to be re-rendered each tick. The - * cached display object can be moved, rotated, faded, etc freely, however if its content changes, you must - * manually update the cache by calling updateCache() or cache() again. You must specify - * the cache area via the x, y, w, and h parameters. This defines the rectangle that will be rendered and cached - * using this display object's coordinates. - * - *

    Example

    - * For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25: - * - * var shape = new createjs.Shape(); - * shape.graphics.beginFill("#ff0000").drawCircle(0, 0, 25); - * myShape.cache(-25, -25, 50, 50); - * - * Note that filters need to be defined before the cache is applied. Check out the {{#crossLink "Filter"}}{{/crossLink}} - * class for more information. Some filters (ex. BlurFilter) will not work as expected in conjunction with the scale param. - * - * Usually, the resulting cacheCanvas will have the dimensions width*scale by height*scale, however some filters (ex. BlurFilter) - * will add padding to the canvas dimensions. - * - * @method cache - * @param {Number} x The x coordinate origin for the cache region. - * @param {Number} y The y coordinate origin for the cache region. - * @param {Number} width The width of the cache region. - * @param {Number} height The height of the cache region. - * @param {Number} [scale=1] The scale at which the cache will be created. For example, if you cache a vector shape using - * myShape.cache(0,0,100,100,2) then the resulting cacheCanvas will be 200x200 px. This lets you scale and rotate - * cached elements with greater fidelity. Default is 1. + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. **/ - p.cache = function(x, y, width, height, scale) { - // draw to canvas. - scale = scale||1; - if (!this.cacheCanvas) { this.cacheCanvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); } - this._cacheWidth = width; - this._cacheHeight = height; - this._cacheOffsetX = x; - this._cacheOffsetY = y; - this._cacheScale = scale; - this.updateCache(); + p.toString = function() { + return "[Sprite (name="+ this.name +")]"; }; +// private methods: /** - * Redraws the display object to its cache. Calling updateCache without an active cache will throw an error. - * If compositeOperation is null the current cache will be cleared prior to drawing. Otherwise the display object - * will be drawn over the existing cache using the specified compositeOperation. - * - *

    Example

    - * Clear the current graphics of a cached shape, draw some new instructions, and then update the cache. The new line - * will be drawn on top of the old one. - * - * // Not shown: Creating the shape, and caching it. - * shapeInstance.clear(); - * shapeInstance.setStrokeStyle(3).beginStroke("#ff0000").moveTo(100, 100).lineTo(200,200); - * shapeInstance.updateCache(); - * - * @method updateCache - * @param {String} compositeOperation The compositeOperation to use, or null to clear the cache and redraw it. - * - * whatwg spec on compositing. + * @method _cloneProps + * @param {Sprite} o + * @return {Sprite} o + * @protected **/ - p.updateCache = function(compositeOperation) { - var cacheCanvas = this.cacheCanvas; - if (!cacheCanvas) { throw "cache() must be called before updateCache()"; } - var scale = this._cacheScale, offX = this._cacheOffsetX*scale, offY = this._cacheOffsetY*scale; - var w = this._cacheWidth, h = this._cacheHeight, ctx = cacheCanvas.getContext("2d"); - - var fBounds = this._getFilterBounds(); - offX += (this._filterOffsetX = fBounds.x); - offY += (this._filterOffsetY = fBounds.y); + p._cloneProps = function(o) { + this.DisplayObject__cloneProps(o); + o.currentFrame = this.currentFrame; + o.currentAnimation = this.currentAnimation; + o.paused = this.paused; + o.currentAnimationFrame = this.currentAnimationFrame; + o.framerate = this.framerate; - w = Math.ceil(w*scale) + fBounds.width; - h = Math.ceil(h*scale) + fBounds.height; - if (w != cacheCanvas.width || h != cacheCanvas.height) { - // TODO: it would be nice to preserve the content if there is a compositeOperation. - cacheCanvas.width = w; - cacheCanvas.height = h; - } else if (!compositeOperation) { - ctx.clearRect(0, 0, w+1, h+1); + o._animation = this._animation; + o._currentFrame = this._currentFrame; + o._skipAdvance = this._skipAdvance; + return o; + }; + + /** + * Advances the currentFrame if paused is not true. This is called automatically when the {{#crossLink "Stage"}}{{/crossLink}} + * ticks. + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * @protected + * @method _tick + **/ + p._tick = function(evtObj) { + if (!this.paused) { + if (!this._skipAdvance) { this.advance(evtObj&&evtObj.delta); } + this._skipAdvance = false; } + this.DisplayObject__tick(evtObj); + }; + + + /** + * Normalizes the current frame, advancing animations and dispatching callbacks as appropriate. + * @protected + * @method _normalizeFrame + **/ + p._normalizeFrame = function(frameDelta) { + frameDelta = frameDelta || 0; + var animation = this._animation; + var paused = this.paused; + var frame = this._currentFrame; + var l; - ctx.save(); - ctx.globalCompositeOperation = compositeOperation; - ctx.setTransform(scale, 0, 0, scale, -offX, -offY); - this.draw(ctx, true); - // TODO: filters and cache scale don't play well together at present. - this._applyFilters(); - ctx.restore(); - this.cacheID = DisplayObject._nextCacheID++; + if (animation) { + var speed = animation.speed || 1; + var animFrame = this.currentAnimationFrame; + l = animation.frames.length; + if (animFrame + frameDelta * speed >= l) { + var next = animation.next; + if (this._dispatchAnimationEnd(animation, frame, paused, next, l - 1)) { + // something changed in the event stack, so we shouldn't make any more changes here. + return; + } else if (next) { + // sequence. Automatically calls _normalizeFrame again with the remaining frames. + return this._goto(next, frameDelta - (l - animFrame) / speed); + } else { + // end. + this.paused = true; + animFrame = animation.frames.length - 1; + } + } else { + animFrame += frameDelta * speed; + } + this.currentAnimationFrame = animFrame; + this._currentFrame = animation.frames[animFrame | 0] + } else { + frame = (this._currentFrame += frameDelta); + l = this.spriteSheet.getNumFrames(); + if (frame >= l && l > 0) { + if (!this._dispatchAnimationEnd(animation, frame, paused, l - 1)) { + // looped. + if ((this._currentFrame -= l) >= l) { return this._normalizeFrame(); } + } + } + } + frame = this._currentFrame | 0; + if (this.currentFrame != frame) { + this.currentFrame = frame; + this.dispatchEvent("change"); + } }; /** - * Clears the current cache. See {{#crossLink "DisplayObject/cache"}}{{/crossLink}} for more information. - * @method uncache + * Dispatches the "animationend" event. Returns true if a handler changed the animation (ex. calling {{#crossLink "Sprite/stop"}}{{/crossLink}}, + * {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}}, etc.) + * @property _dispatchAnimationEnd + * @private + * @type {Function} **/ - p.uncache = function() { - this._cacheDataURL = this.cacheCanvas = null; - this.cacheID = this._cacheOffsetX = this._cacheOffsetY = this._filterOffsetX = this._filterOffsetY = 0; - this._cacheScale = 1; + p._dispatchAnimationEnd = function(animation, frame, paused, next, end) { + var name = animation ? animation.name : null; + if (this.hasEventListener("animationend")) { + var evt = new createjs.Event("animationend"); + evt.name = name; + evt.next = next; + this.dispatchEvent(evt); + } + // did the animation get changed in the event stack?: + var changed = (this._animation != animation || this._currentFrame != frame); + // if the animation hasn't changed, but the sprite was paused, then we want to stick to the last frame: + if (!changed && !paused && this.paused) { this.currentAnimationFrame = end; changed = true; } + return changed; }; - + /** - * Returns a data URL for the cache, or null if this display object is not cached. - * Uses cacheID to ensure a new data URL is not generated if the cache has not changed. - * @method getCacheDataURL - * @return {String} The image data url for the cache. + * Moves the playhead to the specified frame number or animation. + * @method _goto + * @param {String|Number} frameOrAnimation The frame number or animation that the playhead should move to. + * @param {Boolean} [frame] The frame of the animation to go to. Defaults to 0. + * @protected **/ - p.getCacheDataURL = function() { - if (!this.cacheCanvas) { return null; } - if (this.cacheID != this._cacheDataURLID) { this._cacheDataURL = this.cacheCanvas.toDataURL(); } - return this._cacheDataURL; + p._goto = function(frameOrAnimation, frame) { + this.currentAnimationFrame = 0; + if (isNaN(frameOrAnimation)) { + var data = this.spriteSheet.getAnimation(frameOrAnimation); + if (data) { + this._animation = data; + this.currentAnimation = frameOrAnimation; + this._normalizeFrame(frame); + } + } else { + this.currentAnimation = this._animation = null; + this._currentFrame = frameOrAnimation; + this._normalizeFrame(); + } }; + + createjs.Sprite = createjs.promote(Sprite, "DisplayObject"); +}()); + +//############################################################################## +// Shape.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: /** - * Transforms the specified x and y position from the coordinate space of the display object - * to the global (stage) coordinate space. For example, this could be used to position an HTML label - * over a specific point on a nested display object. Returns a Point instance with x and y properties - * correlating to the transformed coordinates on the stage. + * A Shape allows you to display vector art in the display list. It composites a {{#crossLink "Graphics"}}{{/crossLink}} + * instance which exposes all of the vector drawing methods. The Graphics instance can be shared between multiple Shape + * instances to display the same vector graphics with different positions or transforms. + * + * If the vector art will not + * change between draws, you may want to use the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method to reduce the + * rendering cost. * *

    Example

    * - * displayObject.x = 300; - * displayObject.y = 200; - * stage.addChild(displayObject); - * var point = myDisplayObject.localToGlobal(100, 100); - * // Results in x=400, y=300 + * var graphics = new createjs.Graphics().beginFill("#ff0000").drawRect(0, 0, 100, 100); + * var shape = new createjs.Shape(graphics); * - * @method localToGlobal - * @param {Number} x The x position in the source display object to transform. - * @param {Number} y The y position in the source display object to transform. - * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. - * @return {Point} A Point instance with x and y properties correlating to the transformed coordinates - * on the stage. + * //Alternatively use can also use the graphics property of the Shape class to renderer the same as above. + * var shape = new createjs.Shape(); + * shape.graphics.beginFill("#ff0000").drawRect(0, 0, 100, 100); + * + * @class Shape + * @extends DisplayObject + * @constructor + * @param {Graphics} graphics Optional. The graphics instance to display. If null, a new Graphics instance will be created. + **/ + function Shape(graphics) { + this.DisplayObject_constructor(); + + + // public properties: + /** + * The graphics instance to display. + * @property graphics + * @type Graphics + **/ + this.graphics = graphics ? graphics : new createjs.Graphics(); + } + var p = createjs.extend(Shape, createjs.DisplayObject); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** + * Returns true or false indicating whether the Shape would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the Shape would be visible if drawn to a canvas **/ - p.localToGlobal = function(x, y, pt) { - return this.getConcatenatedMatrix(this._props.matrix).transformPoint(x,y, pt||new createjs.Point()); + p.isVisible = function() { + var hasContent = this.cacheCanvas || (this.graphics && !this.graphics.isEmpty()); + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); }; /** - * Transforms the specified x and y position from the global (stage) coordinate space to the - * coordinate space of the display object. For example, this could be used to determine - * the current mouse position within the display object. Returns a Point instance with x and y properties - * correlating to the transformed position in the display object's coordinate space. - * - *

    Example

    - * - * displayObject.x = 300; - * displayObject.y = 200; - * stage.addChild(displayObject); - * var point = myDisplayObject.globalToLocal(100, 100); - * // Results in x=-200, y=-100 + * Draws the Shape into the specified context ignoring its visible, alpha, shadow, and transform. Returns true if + * the draw was handled (useful for overriding functionality). * - * @method globalToLocal - * @param {Number} x The x position on the stage to transform. - * @param {Number} y The y position on the stage to transform. - * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. - * @return {Point} A Point instance with x and y properties correlating to the transformed position in the - * display object's coordinate space. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. For example, + * used for drawing the cache (to prevent it from simply drawing an existing cache back into itself). + * @return {Boolean} **/ - p.globalToLocal = function(x, y, pt) { - return this.getConcatenatedMatrix(this._props.matrix).invert().transformPoint(x,y, pt||new createjs.Point()); + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + this.graphics.draw(ctx, this); + return true; }; /** - * Transforms the specified x and y position from the coordinate space of this display object to the coordinate - * space of the target display object. Returns a Point instance with x and y properties correlating to the - * transformed position in the target's coordinate space. Effectively the same as using the following code with - * {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} and {{#crossLink "DisplayObject/globalToLocal"}}{{/crossLink}}. - * - * var pt = this.localToGlobal(x, y); - * pt = target.globalToLocal(pt.x, pt.y); - * - * @method localToLocal - * @param {Number} x The x position in the source display object to transform. - * @param {Number} y The y position on the source display object to transform. - * @param {DisplayObject} target The target display object to which the coordinates will be transformed. - * @param {Point | Object} [pt] An object to copy the result into. If omitted a new Point object with x/y properties will be returned. - * @return {Point} Returns a Point instance with x and y properties correlating to the transformed position - * in the target's coordinate space. + * Returns a clone of this Shape. Some properties that are specific to this instance's current context are reverted to + * their defaults (for example .parent). + * @method clone + * @param {Boolean} recursive If true, this Shape's {{#crossLink "Graphics"}}{{/crossLink}} instance will also be + * cloned. If false, the Graphics instance will be shared with the new Shape. **/ - p.localToLocal = function(x, y, target, pt) { - pt = this.localToGlobal(x, y, pt); - return target.globalToLocal(pt.x, pt.y, pt); + p.clone = function(recursive) { + var g = (recursive && this.graphics) ? this.graphics.clone() : this.graphics; + return this._cloneProps(new Shape(g)); }; /** - * Shortcut method to quickly set the transform properties on the display object. All parameters are optional. - * Omitted parameters will have the default value set. + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Shape (name="+ this.name +")]"; + }; + + + createjs.Shape = createjs.promote(Shape, "DisplayObject"); +}()); + +//############################################################################## +// Text.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Display one or more lines of dynamic text (not user editable) in the display list. Line wrapping support (using the + * lineWidth) is very basic, wrapping on spaces and tabs only. Note that as an alternative to Text, you can position HTML + * text above or below the canvas relative to items in the display list using the {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} + * method, or using {{#crossLink "DOMElement"}}{{/crossLink}}. + * + * Please note that Text does not support HTML text, and can only display one font style at a time. To use + * multiple font styles, you will need to create multiple text instances, and position them manually. * *

    Example

    * - * displayObject.setTransform(100, 100, 2, 2); + * var text = new createjs.Text("Hello World", "20px Arial", "#ff7700"); + * text.x = 100; + * text.textBaseline = "alphabetic"; * - * @method setTransform - * @param {Number} [x=0] The horizontal translation (x position) in pixels - * @param {Number} [y=0] The vertical translation (y position) in pixels - * @param {Number} [scaleX=1] The horizontal scale, as a percentage of 1 - * @param {Number} [scaleY=1] the vertical scale, as a percentage of 1 - * @param {Number} [rotation=0] The rotation, in degrees - * @param {Number} [skewX=0] The horizontal skew factor - * @param {Number} [skewY=0] The vertical skew factor - * @param {Number} [regX=0] The horizontal registration point in pixels - * @param {Number} [regY=0] The vertical registration point in pixels - * @return {DisplayObject} Returns this instance. Useful for chaining commands. - * @chainable - */ - p.setTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, regX, regY) { - this.x = x || 0; - this.y = y || 0; - this.scaleX = scaleX == null ? 1 : scaleX; - this.scaleY = scaleY == null ? 1 : scaleY; - this.rotation = rotation || 0; - this.skewX = skewX || 0; - this.skewY = skewY || 0; - this.regX = regX || 0; - this.regY = regY || 0; - return this; - }; + * CreateJS Text supports web fonts (the same rules as Canvas). The font must be loaded and supported by the browser + * before it can be displayed. + * + * Note: Text can be expensive to generate, so cache instances where possible. Be aware that not all + * browsers will render Text exactly the same. + * @class Text + * @extends DisplayObject + * @constructor + * @param {String} [text] The text to display. + * @param {String} [font] The font style to use. Any valid value for the CSS font attribute is acceptable (ex. "bold + * 36px Arial"). + * @param {String} [color] The color to draw the text in. Any valid value for the CSS color attribute is acceptable (ex. + * "#F00", "red", or "#FF0000"). + **/ + function Text(text, font, color) { + this.DisplayObject_constructor(); + + + // public properties: + /** + * The text to display. + * @property text + * @type String + **/ + this.text = text; + + /** + * The font style to use. Any valid value for the CSS font attribute is acceptable (ex. "bold 36px Arial"). + * @property font + * @type String + **/ + this.font = font; + + /** + * The color to draw the text in. Any valid value for the CSS color attribute is acceptable (ex. "#F00"). Default is "#000". + * It will also accept valid canvas fillStyle values. + * @property color + * @type String + **/ + this.color = color; + + /** + * The horizontal text alignment. Any of "start", "end", "left", "right", and "center". For detailed + * information view the + * + * whatwg spec. Default is "left". + * @property textAlign + * @type String + **/ + this.textAlign = "left"; + + /** + * The vertical alignment point on the font. Any of "top", "hanging", "middle", "alphabetic", "ideographic", or + * "bottom". For detailed information view the + * whatwg spec. Default is "top". + * @property textBaseline + * @type String + */ + this.textBaseline = "top"; + /** + * The maximum width to draw the text. If maxWidth is specified (not null), the text will be condensed or + * shrunk to make it fit in this width. For detailed information view the + * + * whatwg spec. + * @property maxWidth + * @type Number + */ + this.maxWidth = null; + + /** + * If greater than 0, the text will be drawn as a stroke (outline) of the specified width. + * @property outline + * @type Number + **/ + this.outline = 0; + + /** + * Indicates the line height (vertical distance between baselines) for multi-line text. If null or 0, + * the value of getMeasuredLineHeight is used. + * @property lineHeight + * @type Number + **/ + this.lineHeight = 0; + + /** + * Indicates the maximum width for a line of text before it is wrapped to multiple lines. If null, + * the text will not be wrapped. + * @property lineWidth + * @type Number + **/ + this.lineWidth = null; + } + var p = createjs.extend(Text, createjs.DisplayObject); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// static properties: /** - * Returns a matrix based on this object's current transform. - * @method getMatrix - * @param {Matrix2D} matrix Optional. A Matrix2D object to populate with the calculated values. If null, a new - * Matrix object is returned. - * @return {Matrix2D} A matrix representing this display object's transform. + * @property _workingContext + * @type CanvasRenderingContext2D + * @private **/ - p.getMatrix = function(matrix) { - var o = this, mtx = matrix&&matrix.identity() || new createjs.Matrix2D(); - return o.transformMatrix ? mtx.copy(o.transformMatrix) : mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.regX, o.regY); - }; + var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); + if (canvas.getContext) { Text._workingContext = canvas.getContext("2d"); canvas.width = canvas.height = 1; } + +// constants: /** - * Generates a Matrix2D object representing the combined transform of the display object and all of its - * parent Containers up to the highest level ancestor (usually the {{#crossLink "Stage"}}{{/crossLink}}). This can - * be used to transform positions between coordinate spaces, such as with {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} - * and {{#crossLink "DisplayObject/globalToLocal"}}{{/crossLink}}. - * @method getConcatenatedMatrix - * @param {Matrix2D} [matrix] A {{#crossLink "Matrix2D"}}{{/crossLink}} object to populate with the calculated values. - * If null, a new Matrix2D object is returned. - * @return {Matrix2D} The combined matrix. + * Lookup table for the ratio to offset bounds x calculations based on the textAlign property. + * @property H_OFFSETS + * @type Object + * @protected + * @static **/ - p.getConcatenatedMatrix = function(matrix) { - var o = this, mtx = this.getMatrix(matrix); - while (o = o.parent) { - mtx.prependMatrix(o.getMatrix(o._props.matrix)); - } - return mtx; - }; + Text.H_OFFSETS = {start: 0, left: 0, center: -0.5, end: -1, right: -1}; /** - * Generates a DisplayProps object representing the combined display properties of the object and all of its - * parent Containers up to the highest level ancestor (usually the {{#crossLink "Stage"}}{{/crossLink}}). - * @method getConcatenatedDisplayProps - * @param {DisplayProps} [props] A {{#crossLink "DisplayProps"}}{{/crossLink}} object to populate with the calculated values. - * If null, a new DisplayProps object is returned. - * @return {DisplayProps} The combined display properties. + * Lookup table for the ratio to offset bounds y calculations based on the textBaseline property. + * @property H_OFFSETS + * @type Object + * @protected + * @static **/ - p.getConcatenatedDisplayProps = function(props) { - props = props ? props.identity() : new createjs.DisplayProps(); - var o = this, mtx = o.getMatrix(props.matrix); - do { - props.prepend(o.visible, o.alpha, o.shadow, o.compositeOperation); - - // we do this to avoid problems with the matrix being used for both operations when o._props.matrix is passed in as the props param. - // this could be simplified (ie. just done as part of the prepend above) if we switched to using a pool. - if (o != this) { mtx.prependMatrix(o.getMatrix(o._props.matrix)); } - } while (o = o.parent); - return props; + Text.V_OFFSETS = {top: 0, hanging: -0.01, middle: -0.4, alphabetic: -0.8, ideographic: -0.85, bottom: -1}; + + +// public methods: + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Whether the display object would be visible if drawn to a canvas + **/ + p.isVisible = function() { + var hasContent = this.cacheCanvas || (this.text != null && this.text !== ""); + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); }; /** - * Tests whether the display object intersects the specified point in local coordinates (ie. draws a pixel with alpha > 0 at - * the specified position). This ignores the alpha, shadow, hitArea, mask, and compositeOperation of the display object. - * - *

    Example

    - * - * stage.addEventListener("stagemousedown", handleMouseDown); - * function handleMouseDown(event) { - * var hit = myShape.hitTest(event.stageX, event.stageY); - * } - * - * Please note that shape-to-shape collision is not currently supported by EaselJS. - * @method hitTest - * @param {Number} x The x position to check in the display object's local coordinates. - * @param {Number} y The y position to check in the display object's local coordinates. - * @return {Boolean} A Boolean indicating whether a visible portion of the DisplayObject intersect the specified - * local Point. - */ - p.hitTest = function(x, y) { - var ctx = DisplayObject._hitTestContext; - ctx.setTransform(1, 0, 0, 1, -x, -y); - this.draw(ctx); + * Draws the Text into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } - var hit = this._testHit(ctx); - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.clearRect(0, 0, 2, 2); - return hit; + var col = this.color || "#000"; + if (this.outline) { ctx.strokeStyle = col; ctx.lineWidth = this.outline*1; } + else { ctx.fillStyle = col; } + + this._drawText(this._prepContext(ctx)); + return true; }; - + /** - * Provides a chainable shortcut method for setting a number of properties on the instance. - * - *

    Example

    - * - * var myGraphics = new createjs.Graphics().beginFill("#ff0000").drawCircle(0, 0, 25); - * var shape = stage.addChild(new Shape()).set({graphics:myGraphics, x:100, y:100, alpha:0.5}); - * - * @method set - * @param {Object} props A generic object containing properties to copy to the DisplayObject instance. - * @return {DisplayObject} Returns the instance the method is called on (useful for chaining calls.) - * @chainable - */ - p.set = function(props) { - for (var n in props) { this[n] = props[n]; } - return this; + * Returns the measured, untransformed width of the text without wrapping. Use getBounds for a more robust value. + * @method getMeasuredWidth + * @return {Number} The measured, untransformed width of the text. + **/ + p.getMeasuredWidth = function() { + return this._getMeasuredWidth(this.text); }; - + /** - * Returns a rectangle representing this object's bounds in its local coordinate system (ie. with no transformation). - * Objects that have been cached will return the bounds of the cache. - * - * Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use - * {{#crossLink "DisplayObject/setBounds"}}{{/crossLink}} so that they are included when calculating Container - * bounds. - * - * - * - * - * - * - * - * - * - *
    All - * All display objects support setting bounds manually using setBounds(). Likewise, display objects that - * have been cached using cache() will return the bounds of their cache. Manual and cache bounds will override - * the automatic calculations listed below. - *
    Bitmap - * Returns the width and height of the sourceRect (if specified) or image, extending from (x=0,y=0). - *
    Sprite - * Returns the bounds of the current frame. May have non-zero x/y if a frame registration point was specified - * in the spritesheet data. See also {{#crossLink "SpriteSheet/getFrameBounds"}}{{/crossLink}} - *
    Container - * Returns the aggregate (combined) bounds of all children that return a non-null value from getBounds(). - *
    Shape - * Does not currently support automatic bounds calculations. Use setBounds() to manually define bounds. - *
    Text - * Returns approximate bounds. Horizontal values (x/width) are quite accurate, but vertical values (y/height) are - * not, especially when using textBaseline values other than "top". - *
    BitmapText - * Returns approximate bounds. Values will be more accurate if spritesheet frame registration points are close - * to (x=0,y=0). - *
    - * - * Bounds can be expensive to calculate for some objects (ex. text, or containers with many children), and - * are recalculated each time you call getBounds(). You can prevent recalculation on static objects by setting the - * bounds explicitly: - * - * var bounds = obj.getBounds(); - * obj.setBounds(bounds.x, bounds.y, bounds.width, bounds.height); - * // getBounds will now use the set values, instead of recalculating - * - * To reduce memory impact, the returned Rectangle instance may be reused internally; clone the instance or copy its - * values if you need to retain it. - * - * var myBounds = obj.getBounds().clone(); - * // OR: - * myRect.copy(obj.getBounds()); - * - * @method getBounds - * @return {Rectangle} A Rectangle instance representing the bounds, or null if bounds are not available for this - * object. + * Returns an approximate line height of the text, ignoring the lineHeight property. This is based on the measured + * width of a "M" character multiplied by 1.2, which provides an approximate line height for most fonts. + * @method getMeasuredLineHeight + * @return {Number} an approximate line height of the text, ignoring the lineHeight property. This is + * based on the measured width of a "M" character multiplied by 1.2, which approximates em for most fonts. **/ - p.getBounds = function() { - if (this._bounds) { return this._rectangle.copy(this._bounds); } - var cacheCanvas = this.cacheCanvas; - if (cacheCanvas) { - var scale = this._cacheScale; - return this._rectangle.setValues(this._cacheOffsetX, this._cacheOffsetY, cacheCanvas.width/scale, cacheCanvas.height/scale); - } - return null; + p.getMeasuredLineHeight = function() { + return this._getMeasuredWidth("M")*1.2; }; - + /** - * Returns a rectangle representing this object's bounds in its parent's coordinate system (ie. with transformations applied). - * Objects that have been cached will return the transformed bounds of the cache. - * - * Not all display objects can calculate their own bounds (ex. Shape). For these objects, you can use - * {{#crossLink "DisplayObject/setBounds"}}{{/crossLink}} so that they are included when calculating Container - * bounds. - * - * To reduce memory impact, the returned Rectangle instance may be reused internally; clone the instance or copy its - * values if you need to retain it. - * - * Container instances calculate aggregate bounds for all children that return bounds via getBounds. - * @method getTransformedBounds - * @return {Rectangle} A Rectangle instance representing the bounds, or null if bounds are not available for this object. + * Returns the approximate height of multi-line text by multiplying the number of lines against either the + * lineHeight (if specified) or {{#crossLink "Text/getMeasuredLineHeight"}}{{/crossLink}}. Note that + * this operation requires the text flowing logic to run, which has an associated CPU cost. + * @method getMeasuredHeight + * @return {Number} The approximate height of the untransformed multi-line text. **/ - p.getTransformedBounds = function() { - return this._getBounds(); + p.getMeasuredHeight = function() { + return this._drawText(null,{}).height; + }; + + /** + * Docced in superclass. + */ + p.getBounds = function() { + var rect = this.DisplayObject_getBounds(); + if (rect) { return rect; } + if (this.text == null || this.text === "") { return null; } + var o = this._drawText(null, {}); + var w = (this.maxWidth && this.maxWidth < o.width) ? this.maxWidth : o.width; + var x = w * Text.H_OFFSETS[this.textAlign||"left"]; + var lineHeight = this.lineHeight||this.getMeasuredLineHeight(); + var y = lineHeight * Text.V_OFFSETS[this.textBaseline||"top"]; + return this._rectangle.setValues(x, y, w, o.height); }; /** - * Allows you to manually specify the bounds of an object that either cannot calculate their own bounds (ex. Shape & - * Text) for future reference, or so the object can be included in Container bounds. Manually set bounds will always - * override calculated bounds. - * - * The bounds should be specified in the object's local (untransformed) coordinates. For example, a Shape instance - * with a 25px radius circle centered at 0,0 would have bounds of (-25, -25, 50, 50). - * @method setBounds - * @param {Number} x The x origin of the bounds. Pass null to remove the manual bounds. - * @param {Number} y The y origin of the bounds. - * @param {Number} width The width of the bounds. - * @param {Number} height The height of the bounds. + * Returns an object with width, height, and lines properties. The width and height are the visual width and height + * of the drawn text. The lines property contains an array of strings, one for + * each line of text that will be drawn, accounting for line breaks and wrapping. These strings have trailing + * whitespace removed. + * @method getMetrics + * @return {Object} An object with width, height, and lines properties. **/ - p.setBounds = function(x, y, width, height) { - if (x == null) { this._bounds = x; } - this._bounds = (this._bounds || new createjs.Rectangle()).setValues(x, y, width, height); + p.getMetrics = function() { + var o = {lines:[]}; + o.lineHeight = this.lineHeight || this.getMeasuredLineHeight(); + o.vOffset = o.lineHeight * Text.V_OFFSETS[this.textBaseline||"top"]; + return this._drawText(null, o, o.lines); }; /** - * Returns a clone of this DisplayObject. Some properties that are specific to this instance's current context are - * reverted to their defaults (for example .parent). Caches are not maintained across clones, and some elements - * are copied by reference (masks, individual filter instances, hit area) + * Returns a clone of the Text instance. * @method clone - * @return {DisplayObject} A clone of the current DisplayObject instance. + * @return {Text} a clone of the Text instance. **/ p.clone = function() { - return this._cloneProps(new DisplayObject()); + return this._cloneProps(new Text(this.text, this.font, this.color)); }; /** @@ -6894,278 +10040,802 @@ this.createjs = this.createjs||{}; * @return {String} a string representation of the instance. **/ p.toString = function() { - return "[DisplayObject (name="+ this.name +")]"; + return "[Text (text="+ (this.text.length > 20 ? this.text.substr(0, 17)+"..." : this.text) +")]"; }; // private methods: - // separated so it can be used more easily in subclasses: /** * @method _cloneProps - * @param {DisplayObject} o The DisplayObject instance which will have properties from the current DisplayObject - * instance copied into. - * @return {DisplayObject} o + * @param {Text} o * @protected + * @return {Text} o **/ p._cloneProps = function(o) { - o.alpha = this.alpha; - o.mouseEnabled = this.mouseEnabled; - o.tickEnabled = this.tickEnabled; - o.name = this.name; - o.regX = this.regX; - o.regY = this.regY; - o.rotation = this.rotation; - o.scaleX = this.scaleX; - o.scaleY = this.scaleY; - o.shadow = this.shadow; - o.skewX = this.skewX; - o.skewY = this.skewY; - o.visible = this.visible; - o.x = this.x; - o.y = this.y; - o.compositeOperation = this.compositeOperation; - o.snapToPixel = this.snapToPixel; - o.filters = this.filters==null?null:this.filters.slice(0); - o.mask = this.mask; - o.hitArea = this.hitArea; - o.cursor = this.cursor; - o._bounds = this._bounds; + this.DisplayObject__cloneProps(o); + o.textAlign = this.textAlign; + o.textBaseline = this.textBaseline; + o.maxWidth = this.maxWidth; + o.outline = this.outline; + o.lineHeight = this.lineHeight; + o.lineWidth = this.lineWidth; + return o; + }; + + /** + * @method _getWorkingContext + * @param {CanvasRenderingContext2D} ctx + * @return {CanvasRenderingContext2D} + * @protected + **/ + p._prepContext = function(ctx) { + ctx.font = this.font||"10px sans-serif"; + ctx.textAlign = this.textAlign||"left"; + ctx.textBaseline = this.textBaseline||"top"; + return ctx; + }; + + /** + * Draws multiline text. + * @method _drawText + * @param {CanvasRenderingContext2D} ctx + * @param {Object} o + * @param {Array} lines + * @return {Object} + * @protected + **/ + p._drawText = function(ctx, o, lines) { + var paint = !!ctx; + if (!paint) { + ctx = Text._workingContext; + ctx.save(); + this._prepContext(ctx); + } + var lineHeight = this.lineHeight||this.getMeasuredLineHeight(); + + var maxW = 0, count = 0; + var hardLines = String(this.text).split(/(?:\r\n|\r|\n)/); + for (var i=0, l=hardLines.length; i this.lineWidth) { + // text wrapping: + var words = str.split(/(\s)/); + str = words[0]; + w = ctx.measureText(str).width; + + for (var j=1, jl=words.length; j this.lineWidth) { + if (paint) { this._drawTextLine(ctx, str, count*lineHeight); } + if (lines) { lines.push(str); } + if (w > maxW) { maxW = w; } + str = words[j+1]; + w = ctx.measureText(str).width; + count++; + } else { + str += words[j] + words[j+1]; + w += wordW; + } + } + } + + if (paint) { this._drawTextLine(ctx, str, count*lineHeight); } + if (lines) { lines.push(str); } + if (o && w == null) { w = ctx.measureText(str).width; } + if (w > maxW) { maxW = w; } + count++; + } + + if (o) { + o.width = maxW; + o.height = count*lineHeight; + } + if (!paint) { ctx.restore(); } return o; }; - + + /** + * @method _drawTextLine + * @param {CanvasRenderingContext2D} ctx + * @param {String} text + * @param {Number} y + * @protected + **/ + p._drawTextLine = function(ctx, text, y) { + // Chrome 17 will fail to draw the text if the last param is included but null, so we feed it a large value instead: + if (this.outline) { ctx.strokeText(text, 0, y, this.maxWidth||0xFFFF); } + else { ctx.fillText(text, 0, y, this.maxWidth||0xFFFF); } + }; + + + /** + * @method _getMeasuredWidth + * @param {String} text + * @protected + **/ + p._getMeasuredWidth = function(text) { + var ctx = Text._workingContext; + ctx.save(); + var w = this._prepContext(ctx).measureText(text).width; + ctx.restore(); + return w; + }; + + + createjs.Text = createjs.promote(Text, "DisplayObject"); +}()); + +//############################################################################## +// BitmapText.js +//############################################################################## + +this.createjs = this.createjs || {}; + +(function () { + "use strict"; + + +// constructor: + /** + * Displays text using bitmap glyphs defined in a sprite sheet. Multi-line text is supported + * using new line characters, but automatic wrapping is not supported. See the + * {{#crossLink "BitmapText/spriteSheet:property"}}{{/crossLink}} + * property for more information on defining glyphs. + * + * Important: BitmapText extends Container, but is not designed to be used as one. + * As such, methods like addChild and removeChild are disabled. + * @class BitmapText + * @extends DisplayObject + * @param {String} [text=""] The text to display. + * @param {SpriteSheet} [spriteSheet=null] The spritesheet that defines the character glyphs. + * @constructor + **/ + function BitmapText(text, spriteSheet) { + this.Container_constructor(); + + + // public properties: + /** + * The text to display. + * @property text + * @type String + * @default "" + **/ + this.text = text||""; + + /** + * A SpriteSheet instance that defines the glyphs for this bitmap text. Each glyph/character + * should have a single frame animation defined in the sprite sheet named the same as + * corresponding character. For example, the following animation definition: + * + * "A": {frames: [0]} + * + * would indicate that the frame at index 0 of the spritesheet should be drawn for the "A" character. The short form + * is also acceptable: + * + * "A": 0 + * + * Note that if a character in the text is not found in the sprite sheet, it will also + * try to use the alternate case (upper or lower). + * + * See SpriteSheet for more information on defining sprite sheet data. + * @property spriteSheet + * @type SpriteSheet + * @default null + **/ + this.spriteSheet = spriteSheet; + + /** + * The height of each line of text. If 0, then it will use a line height calculated + * by checking for the height of the "1", "T", or "L" character (in that order). If + * those characters are not defined, it will use the height of the first frame of the + * sprite sheet. + * @property lineHeight + * @type Number + * @default 0 + **/ + this.lineHeight = 0; + + /** + * This spacing (in pixels) will be added after each character in the output. + * @property letterSpacing + * @type Number + * @default 0 + **/ + this.letterSpacing = 0; + + /** + * If a space character is not defined in the sprite sheet, then empty pixels equal to + * spaceWidth will be inserted instead. If 0, then it will use a value calculated + * by checking for the width of the "1", "l", "E", or "A" character (in that order). If + * those characters are not defined, it will use the width of the first frame of the + * sprite sheet. + * @property spaceWidth + * @type Number + * @default 0 + **/ + this.spaceWidth = 0; + + + // private properties: + /** + * @property _oldProps + * @type Object + * @protected + **/ + this._oldProps = {text:0,spriteSheet:0,lineHeight:0,letterSpacing:0,spaceWidth:0}; + } + var p = createjs.extend(BitmapText, createjs.Container); + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + +// static properties: + /** + * BitmapText uses Sprite instances to draw text. To reduce the creation and destruction of instances (and thus garbage collection), it maintains + * an internal object pool of sprite instances to reuse. Increasing this value can cause more sprites to be + * retained, slightly increasing memory use, but reducing instantiation. + * @property maxPoolSize + * @type Number + * @static + * @default 100 + **/ + BitmapText.maxPoolSize = 100; + + /** + * Sprite object pool. + * @type {Array} + * @static + * @private + */ + BitmapText._spritePool = []; + + +// public methods: + /** + * Docced in superclass. + **/ + p.draw = function(ctx, ignoreCache) { + if (this.DisplayObject_draw(ctx, ignoreCache)) { return; } + this._updateText(); + this.Container_draw(ctx, ignoreCache); + }; + + /** + * Docced in superclass. + **/ + p.getBounds = function() { + this._updateText(); + return this.Container_getBounds(); + }; + /** - * @method _applyShadow - * @protected - * @param {CanvasRenderingContext2D} ctx - * @param {Shadow} shadow + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas **/ - p._applyShadow = function(ctx, shadow) { - shadow = shadow || Shadow.identity; - ctx.shadowColor = shadow.color; - ctx.shadowOffsetX = shadow.offsetX; - ctx.shadowOffsetY = shadow.offsetY; - ctx.shadowBlur = shadow.blur; + p.isVisible = function() { + var hasContent = this.cacheCanvas || (this.spriteSheet && this.spriteSheet.complete && this.text); + return !!(this.visible && this.alpha > 0 && this.scaleX !== 0 && this.scaleY !== 0 && hasContent); }; + p.clone = function() { + return this._cloneProps(new BitmapText(this.text, this.spriteSheet)); + }; /** - * @method _tick - * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * Disabled in BitmapText. + * @method addChild + **/ + /** + * Disabled in BitmapText. + * @method addChildAt + **/ + /** + * Disabled in BitmapText. + * @method removeChild + **/ + /** + * Disabled in BitmapText. + * @method removeChildAt + **/ + /** + * Disabled in BitmapText. + * @method removeAllChildren + **/ + p.addChild = p.addChildAt = p.removeChild = p.removeChildAt = p.removeAllChildren = function() {}; + + +// private methods: + /** + * @method _cloneProps + * @param {BitmapText} o + * @return {BitmapText} o * @protected **/ - p._tick = function(evtObj) { - // because tick can be really performance sensitive, check for listeners before calling dispatchEvent. - var ls = this._listeners; - if (ls && ls["tick"]) { - // reset & reuse the event object to avoid construction / GC costs: - evtObj.target = null; - evtObj.propagationStopped = evtObj.immediatePropagationStopped = false; - this.dispatchEvent(evtObj); - } + p._cloneProps = function(o) { + this.Container__cloneProps(o); + o.lineHeight = this.lineHeight; + o.letterSpacing = this.letterSpacing; + o.spaceWidth = this.spaceWidth; + return o; }; - + /** - * @method _testHit + * @method _getFrameIndex + * @param {String} character + * @param {SpriteSheet} spriteSheet + * @return {Number} * @protected - * @param {CanvasRenderingContext2D} ctx - * @return {Boolean} **/ - p._testHit = function(ctx) { - try { - var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1; - } catch (e) { - if (!DisplayObject.suppressCrossDomainErrors) { - throw "An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images."; - } + p._getFrameIndex = function(character, spriteSheet) { + var c, o = spriteSheet.getAnimation(character); + if (!o) { + (character != (c = character.toUpperCase())) || (character != (c = character.toLowerCase())) || (c=null); + if (c) { o = spriteSheet.getAnimation(c); } } - return hit; + return o && o.frames[0]; }; - + /** - * @method _applyFilters + * @method _getFrame + * @param {String} character + * @param {SpriteSheet} spriteSheet + * @return {Object} * @protected **/ - p._applyFilters = function() { - if (!this.filters || this.filters.length == 0 || !this.cacheCanvas) { return; } - var l = this.filters.length; - var ctx = this.cacheCanvas.getContext("2d"); - var w = this.cacheCanvas.width; - var h = this.cacheCanvas.height; - for (var i=0; i maxX) { maxX = x; } - if ((x = x_a + y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; } - if ((x = y_c + tx) < minX) { minX = x; } else if (x > maxX) { maxX = x; } - - if ((y = x_b + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } - if ((y = x_b + y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } - if ((y = y_d + ty) < minY) { minY = y; } else if (y > maxY) { maxY = y; } - - return bounds.setValues(minX, minY, maxX-minX, maxY-minY); - }; - - /** - * Indicates whether the display object has any mouse event listeners or a cursor. - * @method _isMouseOpaque - * @return {Boolean} - * @protected - **/ - p._hasMouseEventListener = function() { - var evts = DisplayObject._MOUSE_EVENTS; - for (var i= 0, l=evts.length; i childIndex) { + // faster than removeChild. + pool.push(sprite = kids.pop()); + sprite.parent = null; + numKids--; + } + if (pool.length > BitmapText.maxPoolSize) { pool.length = BitmapText.maxPoolSize; } }; - createjs.DisplayObject = createjs.promote(DisplayObject, "EventDispatcher"); + + createjs.BitmapText = createjs.promote(BitmapText, "Container"); }()); //############################################################################## -// Container.js +// MovieClip.js //############################################################################## this.createjs = this.createjs||{}; (function() { "use strict"; - + // constructor: -/** - * A Container is a nestable display list that allows you to work with compound display elements. For example you could - * group arm, leg, torso and head {{#crossLink "Bitmap"}}{{/crossLink}} instances together into a Person Container, and - * transform them as a group, while still being able to move the individual parts relative to each other. Children of - * containers have their transform and alpha properties concatenated with their parent - * Container. - * - * For example, a {{#crossLink "Shape"}}{{/crossLink}} with x=100 and alpha=0.5, placed in a Container with x=50 - * and alpha=0.7 will be rendered to the canvas at x=150 and alpha=0.35. - * Containers have some overhead, so you generally shouldn't create a Container to hold a single child. - * - *

    Example

    - * - * var container = new createjs.Container(); - * container.addChild(bitmapInstance, shapeInstance); - * container.x = 100; - * - * @class Container - * @extends DisplayObject - * @constructor - **/ - function Container() { - this.DisplayObject_constructor(); + /** + * The MovieClip class associates a TweenJS Timeline with an EaselJS {{#crossLink "Container"}}{{/crossLink}}. It allows + * you to create objects which encapsulate timeline animations, state changes, and synched actions. Due to the + * complexities inherent in correctly setting up a MovieClip, it is largely intended for tool output and is not included + * in the main EaselJS library. + * + * Currently MovieClip only works properly if it is tick based (as opposed to time based) though some concessions have + * been made to support time-based timelines in the future. + * + *

    Example

    + * This example animates two shapes back and forth. The grey shape starts on the left, but we jump to a mid-point in + * the animation using {{#crossLink "MovieClip/gotoAndPlay"}}{{/crossLink}}. + * + * var stage = new createjs.Stage("canvas"); + * createjs.Ticker.addEventListener("tick", stage); + * + * var mc = new createjs.MovieClip(null, 0, true, {start:20}); + * stage.addChild(mc); + * + * var child1 = new createjs.Shape( + * new createjs.Graphics().beginFill("#999999") + * .drawCircle(30,30,30)); + * var child2 = new createjs.Shape( + * new createjs.Graphics().beginFill("#5a9cfb") + * .drawCircle(30,30,30)); + * + * mc.timeline.addTween( + * createjs.Tween.get(child1) + * .to({x:0}).to({x:60}, 50).to({x:0}, 50)); + * mc.timeline.addTween( + * createjs.Tween.get(child2) + * .to({x:60}).to({x:0}, 50).to({x:60}, 50)); + * + * mc.gotoAndPlay("start"); + * + * It is recommended to use tween.to() to animate and set properties (use no duration to have it set + * immediately), and the tween.wait() method to create delays between animations. Note that using the + * tween.set() method to affect properties will likely not provide the desired result. + * + * @class MovieClip + * @main MovieClip + * @extends Container + * @constructor + * @param {String} [mode=independent] Initial value for the mode property. One of {{#crossLink "MovieClip/INDEPENDENT:property"}}{{/crossLink}}, + * {{#crossLink "MovieClip/SINGLE_FRAME:property"}}{{/crossLink}}, or {{#crossLink "MovieClip/SYNCHED:property"}}{{/crossLink}}. + * The default is {{#crossLink "MovieClip/INDEPENDENT:property"}}{{/crossLink}}. + * @param {Number} [startPosition=0] Initial value for the {{#crossLink "MovieClip/startPosition:property"}}{{/crossLink}} + * property. + * @param {Boolean} [loop=true] Initial value for the {{#crossLink "MovieClip/loop:property"}}{{/crossLink}} + * property. The default is `true`. + * @param {Object} [labels=null] A hash of labels to pass to the {{#crossLink "MovieClip/timeline:property"}}{{/crossLink}} + * instance associated with this MovieClip. Labels only need to be passed if they need to be used. + **/ + function MovieClip(mode, startPosition, loop, labels) { + this.Container_constructor(); + !MovieClip.inited&&MovieClip.init(); // static init + // public properties: /** - * The array of children in the display list. You should usually use the child management methods such as - * {{#crossLink "Container/addChild"}}{{/crossLink}}, {{#crossLink "Container/removeChild"}}{{/crossLink}}, - * {{#crossLink "Container/swapChildren"}}{{/crossLink}}, etc, rather than accessing this directly, but it is - * included for advanced uses. - * @property children - * @type Array + * Controls how this MovieClip advances its time. Must be one of 0 (INDEPENDENT), 1 (SINGLE_FRAME), or 2 (SYNCHED). + * See each constant for a description of the behaviour. + * @property mode + * @type String * @default null **/ - this.children = []; - + this.mode = mode||MovieClip.INDEPENDENT; + /** - * Indicates whether the children of this container are independently enabled for mouse/pointer interaction. - * If false, the children will be aggregated under the container - for example, a click on a child shape would - * trigger a click event on the container. - * @property mouseChildren + * Specifies what the first frame to play in this movieclip, or the only frame to display if mode is SINGLE_FRAME. + * @property startPosition + * @type Number + * @default 0 + */ + this.startPosition = startPosition || 0; + + /** + * Indicates whether this MovieClip should loop when it reaches the end of its timeline. + * @property loop + * @type Boolean + * @default true + */ + this.loop = loop; + + /** + * The current frame of the movieclip. + * @property currentFrame + * @type Number + * @default 0 + * @readonly + */ + this.currentFrame = 0; + + /** + * The TweenJS Timeline that is associated with this MovieClip. This is created automatically when the MovieClip + * instance is initialized. Animations are created by adding TweenJS Tween + * instances to the timeline. + * + *

    Example

    + * + * var tween = createjs.Tween.get(target).to({x:0}).to({x:100}, 30); + * var mc = new createjs.MovieClip(); + * mc.timeline.addTween(tween); + * + * Elements can be added and removed from the timeline by toggling an "_off" property + * using the tweenInstance.to() method. Note that using Tween.set is not recommended to + * create MovieClip animations. The following example will toggle the target off on frame 0, and then back on for + * frame 1. You can use the "visible" property to achieve the same effect. + * + * var tween = createjs.Tween.get(target).to({_off:false}) + * .wait(1).to({_off:true}) + * .wait(1).to({_off:false}); + * + * @property timeline + * @type Timeline + * @default null + */ + this.timeline = new createjs.Timeline(null, labels, {paused:true, position:startPosition, useTicks:true}); + + /** + * If true, the MovieClip's position will not advance when ticked. + * @property paused + * @type Boolean + * @default false + */ + this.paused = false; + + /** + * If true, actions in this MovieClip's tweens will be run when the playhead advances. + * @property actionsEnabled + * @type Boolean + * @default true + */ + this.actionsEnabled = true; + + /** + * If true, the MovieClip will automatically be reset to its first frame whenever the timeline adds + * it back onto the display list. This only applies to MovieClip instances with mode=INDEPENDENT. + *

    + * For example, if you had a character animation with a "body" child MovieClip instance + * with different costumes on each frame, you could set body.autoReset = false, so that + * you can manually change the frame it is on, without worrying that it will be reset + * automatically. + * @property autoReset * @type Boolean * @default true + */ + this.autoReset = true; + + /** + * An array of bounds for each frame in the MovieClip. This is mainly intended for tool output. + * @property frameBounds + * @type Array + * @default null + */ + this.frameBounds = this.frameBounds||null; // TODO: Deprecated. This is for backwards support of FlashCC + + /** + * By default MovieClip instances advance one frame per tick. Specifying a framerate for the MovieClip + * will cause it to advance based on elapsed time between ticks as appropriate to maintain the target + * framerate. + * + * For example, if a MovieClip with a framerate of 10 is placed on a Stage being updated at 40fps, then the MovieClip will + * advance roughly one frame every 4 ticks. This will not be exact, because the time between each tick will + * vary slightly between frames. + * + * This feature is dependent on the tick event object (or an object with an appropriate "delta" property) being + * passed into {{#crossLink "Stage/update"}}{{/crossLink}}. + * @property framerate + * @type {Number} + * @default null **/ - this.mouseChildren = true; + this.framerate = null; + + // private properties: + /** + * @property _synchOffset + * @type Number + * @default 0 + * @private + */ + this._synchOffset = 0; + + /** + * @property _prevPos + * @type Number + * @default -1 + * @private + */ + this._prevPos = -1; // TODO: evaluate using a ._reset Boolean prop instead of -1. + /** - * If false, the tick will not be propagated to children of this Container. This can provide some performance benefits. - * In addition to preventing the "tick" event from being dispatched, it will also prevent tick related updates - * on some display objects (ex. Sprite & MovieClip frame advancing, DOMElement visibility handling). - * @property tickChildren - * @type Boolean - * @default true - **/ - this.tickChildren = true; + * @property _prevPosition + * @type Number + * @default 0 + * @private + */ + this._prevPosition = 0; + + /** + * The time remaining from the previous tick, only applicable when .framerate is set. + * @property _t + * @type Number + * @private + */ + this._t = 0; + + /** + * List of display objects that are actively being managed by the MovieClip. + * @property _managed + * @type Object + * @private + */ + this._managed = {}; } - var p = createjs.extend(Container, createjs.DisplayObject); + var p = createjs.extend(MovieClip, createjs.Container); + + +// constants: + /** + * The MovieClip will advance independently of its parent, even if its parent is paused. + * This is the default mode. + * @property INDEPENDENT + * @static + * @type String + * @default "independent" + * @readonly + **/ + MovieClip.INDEPENDENT = "independent"; + + /** + * The MovieClip will only display a single frame (as determined by the startPosition property). + * @property SINGLE_FRAME + * @static + * @type String + * @default "single" + * @readonly + **/ + MovieClip.SINGLE_FRAME = "single"; + + /** + * The MovieClip will be advanced only when its parent advances and will be synched to the position of + * the parent MovieClip. + * @property SYNCHED + * @static + * @type String + * @default "synched" + * @readonly + **/ + MovieClip.SYNCHED = "synched"; + + +// static properties: + MovieClip.inited = false; + + +// static methods: + MovieClip.init = function() { + if (MovieClip.inited) { return; } + // plugins introduce some overhead to Tween, so we only install this if an MC is instantiated. + MovieClipPlugin.install(); + MovieClip.inited = true; + }; // getter / setters: /** - * Use the {{#crossLink "Container/numChildren:property"}}{{/crossLink}} property instead. - * @method getNumChildren - * @return {Number} + * Use the {{#crossLink "MovieClip/labels:property"}}{{/crossLink}} property instead. + * @method getLabels + * @return {Array} * @deprecated **/ - p.getNumChildren = function() { - return this.children.length; + p.getLabels = function() { + return this.timeline.getLabels(); + }; + + /** + * Use the {{#crossLink "MovieClip/currentLabel:property"}}{{/crossLink}} property instead. + * @method getCurrentLabel + * @return {String} + * @deprecated + **/ + p.getCurrentLabel = function() { + this._updateTimeline(); + return this.timeline.getCurrentLabel(); + }; + + /** + * Use the {{#crossLink "MovieClip/duration:property"}}{{/crossLink}} property instead. + * @method getDuration + * @return {Number} + * @protected + **/ + p.getDuration = function() { + return this.timeline.duration; }; /** - * Returns the number of children in the container. - * @property numChildren + * Returns an array of objects with label and position (aka frame) properties, sorted by position. + * Shortcut to TweenJS: Timeline.getLabels(); + * @property labels + * @type {Array} + * @readonly + **/ + + /** + * Returns the name of the label on or immediately before the current frame. See TweenJS: Timeline.getCurrentLabel() + * for more information. + * @property currentLabel + * @type {String} + * @readonly + **/ + + /** + * Returns the duration of this MovieClip in seconds or ticks. Identical to {{#crossLink "MovieClip/duration:property"}}{{/crossLink}} + * and provided for Flash API compatibility. + * @property totalFrames + * @type {Number} + * @readonly + **/ + + /** + * Returns the duration of this MovieClip in seconds or ticks. + * @property duration * @type {Number} * @readonly **/ try { Object.defineProperties(p, { - numChildren: { get: p.getNumChildren } + labels: { get: p.getLabels }, + currentLabel: { get: p.getCurrentLabel }, + totalFrames: { get: p.getDuration }, + duration: { get: p.getDuration } }); } catch (e) {} - + // public methods: /** @@ -7174,413 +10844,874 @@ this.createjs = this.createjs||{}; * @method initialize * @deprecated in favour of `createjs.promote()` **/ - p.initialize = Container; // TODO: deprecated. - + p.initialize = MovieClip; // TODO: Deprecated. This is for backwards support of FlashCC + /** * Returns true or false indicating whether the display object would be visible if drawn to a canvas. * This does not account for whether it would be visible within the boundaries of the stage. - * * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. * @method isVisible * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas **/ p.isVisible = function() { - var hasContent = this.cacheCanvas || this.children.length; - return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); + // children are placed in draw, so we can't determine if we have content. + return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0); }; /** * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. * Returns true if the draw was handled (useful for overriding functionality). - * * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. * @method draw * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. + * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back * into itself). **/ p.draw = function(ctx, ignoreCache) { + // draw to cache first: if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } + this._updateTimeline(); + this.Container_draw(ctx, ignoreCache); + return true; + }; + + /** + * Sets paused to false. + * @method play + **/ + p.play = function() { + this.paused = false; + }; + + /** + * Sets paused to true. + * @method stop + **/ + p.stop = function() { + this.paused = true; + }; + + /** + * Advances this movie clip to the specified position or label and sets paused to false. + * @method gotoAndPlay + * @param {String|Number} positionOrLabel The animation name or frame number to go to. + **/ + p.gotoAndPlay = function(positionOrLabel) { + this.paused = false; + this._goto(positionOrLabel); + }; + + /** + * Advances this movie clip to the specified position or label and sets paused to true. + * @method gotoAndStop + * @param {String|Number} positionOrLabel The animation or frame name to go to. + **/ + p.gotoAndStop = function(positionOrLabel) { + this.paused = true; + this._goto(positionOrLabel); + }; + + /** + * Advances the playhead. This occurs automatically each tick by default. + * @param [time] {Number} The amount of time in ms to advance by. Only applicable if framerate is set. + * @method advance + */ + p.advance = function(time) { + // TODO: should we worry at all about clips who change their own modes via frame scripts? + var independent = MovieClip.INDEPENDENT; + if (this.mode != independent) { return; } - // this ensures we don't have issues with display list changes that occur during a draw: - var list = this.children.slice(); - for (var i=0,l=list.length; iExample - * - * container.addChild(bitmapInstance); - * - * You can also add multiple children at once: - * - * container.addChild(bitmapInstance, shapeInstance, textInstance); - * - * @method addChild - * @param {DisplayObject} child The display object to add. - * @return {DisplayObject} The child that was added, or the last child if multiple children were added. + * MovieClip instances cannot be cloned. + * @method clone **/ - p.addChild = function(child) { - if (child == null) { return child; } - var l = arguments.length; - if (l > 1) { - for (var i=0; i=0; i--) { + var id = kids[i].id; + if (this._managed[id] == 1) { + this.removeChildAt(i); + delete(this._managed[id]); + } } - if (child.parent) { child.parent.removeChild(child); } - child.parent = this; - this.children.push(child); - child.dispatchEvent("added"); - return child; }; /** - * Adds a child to the display list at the specified index, bumping children at equal or greater indexes up one, and - * setting its parent to this Container. - * - *

    Example

    - * - * addChildAt(child1, index); - * - * You can also add multiple children, such as: - * - * addChildAt(child1, child2, ..., index); - * - * The index must be between 0 and numChildren. For example, to add myShape under otherShape in the display list, - * you could use: - * - * container.addChildAt(myShape, container.getChildIndex(otherShape)); - * - * This would also bump otherShape's index up by one. Fails silently if the index is out of range. - * - * @method addChildAt - * @param {DisplayObject} child The display object to add. - * @param {Number} index The index to add the child at. - * @return {DisplayObject} Returns the last child that was added, or the last child if multiple children were added. + * @method _setState + * @param {Array} state + * @param {Number} offset + * @protected + **/ + p._setState = function(state, offset) { + if (!state) { return; } + for (var i=state.length-1;i>=0;i--) { + var o = state[i]; + var target = o.t; + var props = o.p; + for (var n in props) { target[n] = props[n]; } + this._addManagedChild(target, offset); + } + }; + + /** + * Adds a child to the timeline, and sets it up as a managed child. + * @method _addManagedChild + * @param {MovieClip} child The child MovieClip to manage + * @param {Number} offset + * @private + **/ + p._addManagedChild = function(child, offset) { + if (child._off) { return; } + this.addChildAt(child,0); + + if (child instanceof MovieClip) { + child._synchOffset = offset; + // TODO: this does not precisely match Flash. Flash loses track of the clip if it is renamed or removed from the timeline, which causes it to reset. + if (child.mode == MovieClip.INDEPENDENT && child.autoReset && !this._managed[child.id]) { child._reset(); } + } + this._managed[child.id] = 2; + }; + + /** + * @method _getBounds + * @param {Matrix2D} matrix + * @param {Boolean} ignoreTransform + * @return {Rectangle} + * @protected + **/ + p._getBounds = function(matrix, ignoreTransform) { + var bounds = this.DisplayObject_getBounds(); + if (!bounds) { + this._updateTimeline(); + if (this.frameBounds) { bounds = this._rectangle.copy(this.frameBounds[this.currentFrame]); } + } + if (bounds) { return this._transformBounds(bounds, matrix, ignoreTransform); } + return this.Container__getBounds(matrix, ignoreTransform); + }; + + + createjs.MovieClip = createjs.promote(MovieClip, "Container"); + + + +// MovieClipPlugin for TweenJS: + /** + * This plugin works with TweenJS to prevent the startPosition + * property from tweening. + * @private + * @class MovieClipPlugin + * @constructor + **/ + function MovieClipPlugin() { + throw("MovieClipPlugin cannot be instantiated.") + } + + /** + * @method priority + * @private + **/ + MovieClipPlugin.priority = 100; // very high priority, should run first + + /** + * @method install + * @private + **/ + MovieClipPlugin.install = function() { + createjs.Tween.installPlugin(MovieClipPlugin, ["startPosition"]); + }; + + /** + * @method init + * @param {Tween} tween + * @param {String} prop + * @param {String|Number|Boolean} value + * @private + **/ + MovieClipPlugin.init = function(tween, prop, value) { + return value; + }; + + /** + * @method step + * @private **/ - p.addChildAt = function(child, index) { - var l = arguments.length; - var indx = arguments[l-1]; // can't use the same name as the index param or it replaces arguments[1] - if (indx < 0 || indx > this.children.length) { return arguments[l-2]; } - if (l > 2) { - for (var i=0; iExample - * - * container.removeChild(child); - * - * You can also remove multiple children: - * - * removeChild(child1, child2, ...); - * - * Returns true if the child (or children) was removed, or false if it was not in the display list. - * @method removeChild - * @param {DisplayObject} child The child to remove. - * @return {Boolean} true if the child (or children) was removed, or false if it was not in the display list. - **/ - p.removeChild = function(child) { - var l = arguments.length; - if (l > 1) { - var good = true; - for (var i=0; iExample - * - * container.removeChildAt(2); - * - * You can also remove multiple children: - * - * container.removeChild(2, 7, ...) - * - * Returns true if the child (or children) was removed, or false if any index was out of range. - * @method removeChildAt - * @param {Number} index The index of the child to remove. - * @return {Boolean} true if the child (or children) was removed, or false if any index was out of range. + * The SpriteSheetUtils class is a collection of static methods for working with {{#crossLink "SpriteSheet"}}{{/crossLink}}s. + * A sprite sheet is a series of images (usually animation frames) combined into a single image on a regular grid. For + * example, an animation consisting of 8 100x100 images could be combined into a 400x200 sprite sheet (4 frames across + * by 2 high). The SpriteSheetUtils class uses a static interface and should not be instantiated. + * @class SpriteSheetUtils + * @static **/ - p.removeChildAt = function(index) { - var l = arguments.length; - if (l > 1) { - var a = []; - for (var i=0; i this.children.length-1) { return false; } - var child = this.children[index]; - if (child) { child.parent = null; } - this.children.splice(index, 1); - child.dispatchEvent("removed"); - return true; - }; + function SpriteSheetUtils() { + throw "SpriteSheetUtils cannot be instantiated"; + } + +// private static properties: /** - * Removes all children from the display list. - * - *

    Example

    - * - * container.removeAllChildren(); - * - * @method removeAllChildren + * @property _workingCanvas + * @static + * @type HTMLCanvasElement | Object + * @protected + */ + /** + * @property _workingContext + * @static + * @type CanvasRenderingContext2D + * @protected + */ + var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); + if (canvas.getContext) { + SpriteSheetUtils._workingCanvas = canvas; + SpriteSheetUtils._workingContext = canvas.getContext("2d"); + canvas.width = canvas.height = 1; + } + + +// public static methods: + /** + * This is an experimental method, and may be buggy. Please report issues.

    + * Extends the existing sprite sheet by flipping the original frames horizontally, vertically, or both, + * and adding appropriate animation & frame data. The flipped animations will have a suffix added to their names + * (_h, _v, _hv as appropriate). Make sure the sprite sheet images are fully loaded before using this method. + *

    + * For example:
    + * SpriteSheetUtils.addFlippedFrames(mySpriteSheet, true, true); + * The above would add frames that are flipped horizontally AND frames that are flipped vertically. + *

    + * Note that you can also flip any display object by setting its scaleX or scaleY to a negative value. On some + * browsers (especially those without hardware accelerated canvas) this can result in slightly degraded performance, + * which is why addFlippedFrames is available. + * @method addFlippedFrames + * @static + * @param {SpriteSheet} spriteSheet + * @param {Boolean} horizontal If true, horizontally flipped frames will be added. + * @param {Boolean} vertical If true, vertically flipped frames will be added. + * @param {Boolean} both If true, frames that are flipped both horizontally and vertically will be added. + * @deprecated Modern browsers perform better when flipping via a transform (ex. scaleX=-1) rendering this obsolete. **/ - p.removeAllChildren = function() { - var kids = this.children; - while (kids.length) { this.removeChildAt(0); } + SpriteSheetUtils.addFlippedFrames = function(spriteSheet, horizontal, vertical, both) { + if (!horizontal && !vertical && !both) { return; } + + var count = 0; + if (horizontal) { SpriteSheetUtils._flip(spriteSheet,++count,true,false); } + if (vertical) { SpriteSheetUtils._flip(spriteSheet,++count,false,true); } + if (both) { SpriteSheetUtils._flip(spriteSheet,++count,true,true); } }; /** - * Returns the child at the specified index. - * - *

    Example

    + * Returns a single frame of the specified sprite sheet as a new PNG image. An example of when this may be useful is + * to use a spritesheet frame as the source for a bitmap fill. * - * container.getChildAt(2); + * WARNING: In almost all cases it is better to display a single frame using a {{#crossLink "Sprite"}}{{/crossLink}} + * with a {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} call than it is to slice out a frame using this + * method and display it with a Bitmap instance. You can also crop an image using the {{#crossLink "Bitmap/sourceRect"}}{{/crossLink}} + * property of {{#crossLink "Bitmap"}}{{/crossLink}}. * - * @method getChildAt - * @param {Number} index The index of the child to return. - * @return {DisplayObject} The child at the specified index. Returns null if there is no child at the index. - **/ - p.getChildAt = function(index) { - return this.children[index]; + * The extractFrame method may cause cross-domain warnings since it accesses pixels directly on the canvas. + * @method extractFrame + * @static + * @param {SpriteSheet} spriteSheet The SpriteSheet instance to extract a frame from. + * @param {Number|String} frameOrAnimation The frame number or animation name to extract. If an animation + * name is specified, only the first frame of the animation will be extracted. + * @return {HTMLImageElement} a single frame of the specified sprite sheet as a new PNG image. + */ + SpriteSheetUtils.extractFrame = function(spriteSheet, frameOrAnimation) { + if (isNaN(frameOrAnimation)) { + frameOrAnimation = spriteSheet.getAnimation(frameOrAnimation).frames[0]; + } + var data = spriteSheet.getFrame(frameOrAnimation); + if (!data) { return null; } + var r = data.rect; + var canvas = SpriteSheetUtils._workingCanvas; + canvas.width = r.width; + canvas.height = r.height; + SpriteSheetUtils._workingContext.drawImage(data.image, r.x, r.y, r.width, r.height, 0, 0, r.width, r.height); + var img = document.createElement("img"); + img.src = canvas.toDataURL("image/png"); + return img; }; - + /** - * Returns the child with the specified name. - * @method getChildByName - * @param {String} name The name of the child to return. - * @return {DisplayObject} The child with the specified name. - **/ - p.getChildByName = function(name) { - var kids = this.children; - for (var i=0,l=kids.length;iExample: Display children with a higher y in front. - * - * var sortFunction = function(obj1, obj2, options) { - * if (obj1.y > obj2.y) { return 1; } - * if (obj1.y < obj2.y) { return -1; } - * return 0; - * } - * container.sortChildren(sortFunction); - * - * @method sortChildren - * @param {Function} sortFunction the function to use to sort the child list. See JavaScript's Array.sort - * documentation for details. - **/ - p.sortChildren = function(sortFunction) { - this.children.sort(sortFunction); + var sfx = "_"+(h?"h":"")+(v?"v":""); + var names = spriteSheet._animations; + var data = spriteSheet._data; + var al = names.length/count; + for (i=0;iExample + * The SpriteSheetBuilder allows you to generate {{#crossLink "SpriteSheet"}}{{/crossLink}} instances at run time + * from any display object. This can allow you to maintain your assets as vector graphics (for low file size), and + * render them at run time as SpriteSheets for better performance. * - * var index = container.getChildIndex(child); + * SpriteSheets can be built either synchronously, or asynchronously, so that large SpriteSheets can be generated + * without locking the UI. * - * @method getChildIndex - * @param {DisplayObject} child The child to return the index of. - * @return {Number} The index of the specified child. -1 if the child is not found. + * Note that the "images" used in the generated SpriteSheet are actually canvas elements, and that they will be + * sized to the nearest power of 2 up to the value of {{#crossLink "SpriteSheetBuilder/maxWidth:property"}}{{/crossLink}} + * or {{#crossLink "SpriteSheetBuilder/maxHeight:property"}}{{/crossLink}}. + * @class SpriteSheetBuilder + * @param {Number} [framerate=0] The {{#crossLink "SpriteSheet/framerate:property"}}{{/crossLink}} of + * {{#crossLink "SpriteSheet"}}{{/crossLink}} instances that are created. + * @extends EventDispatcher + * @constructor **/ - p.getChildIndex = function(child) { - return createjs.indexOf(this.children, child); - }; + function SpriteSheetBuilder(framerate) { + this.EventDispatcher_constructor(); + + // public properties: + /** + * The maximum width for the images (not individual frames) in the generated SpriteSheet. It is recommended to + * use a power of 2 for this value (ex. 1024, 2048, 4096). If the frames cannot all fit within the max + * dimensions, then additional images will be created as needed. + * @property maxWidth + * @type Number + * @default 2048 + */ + this.maxWidth = 2048; - /** - * Swaps the children at the specified indexes. Fails silently if either index is out of range. - * @method swapChildrenAt - * @param {Number} index1 - * @param {Number} index2 - **/ - p.swapChildrenAt = function(index1, index2) { - var kids = this.children; - var o1 = kids[index1]; - var o2 = kids[index2]; - if (!o1 || !o2) { return; } - kids[index1] = o2; - kids[index2] = o1; - }; + /** + * The maximum height for the images (not individual frames) in the generated SpriteSheet. It is recommended to + * use a power of 2 for this value (ex. 1024, 2048, 4096). If the frames cannot all fit within the max + * dimensions, then additional images will be created as needed. + * @property maxHeight + * @type Number + * @default 2048 + **/ + this.maxHeight = 2048; - /** - * Swaps the specified children's depth in the display list. Fails silently if either child is not a child of this - * Container. - * @method swapChildren - * @param {DisplayObject} child1 - * @param {DisplayObject} child2 - **/ - p.swapChildren = function(child1, child2) { - var kids = this.children; - var index1,index2; - for (var i=0,l=kids.length;i= l) { return; } - for (var i=0;iREMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + +// constants: + SpriteSheetBuilder.ERR_DIMENSIONS = "frame dimensions exceed max spritesheet dimensions"; + SpriteSheetBuilder.ERR_RUNNING = "a build is already running"; + +// events: /** - * Tests whether the display object intersects the specified local point (ie. draws a pixel with alpha > 0 at the - * specified position). This ignores the alpha, shadow and compositeOperation of the display object, and all - * transform properties including regX/Y. - * @method hitTest - * @param {Number} x The x position to check in the display object's local coordinates. - * @param {Number} y The y position to check in the display object's local coordinates. - * @return {Boolean} A Boolean indicating whether there is a visible section of a DisplayObject that overlaps the specified - * coordinates. - **/ - p.hitTest = function(x, y) { - // TODO: optimize to use the fast cache check where possible. - return (this.getObjectUnderPoint(x, y) != null); - }; + * Dispatched when a build completes. + * @event complete + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @since 0.6.0 + */ /** - * Returns an array of all display objects under the specified coordinates that are in this container's display - * list. This routine ignores any display objects with {{#crossLink "DisplayObject/mouseEnabled:property"}}{{/crossLink}} - * set to `false`. The array will be sorted in order of visual depth, with the top-most display object at index 0. - * This uses shape based hit detection, and can be an expensive operation to run, so it is best to use it carefully. - * For example, if testing for objects under the mouse, test on tick (instead of on {{#crossLink "DisplayObject/mousemove:event"}}{{/crossLink}}), - * and only if the mouse's position has changed. - * - *
      - *
    • By default (mode=0) this method evaluates all display objects.
    • - *
    • By setting the `mode` parameter to `1`, the {{#crossLink "DisplayObject/mouseEnabled:property"}}{{/crossLink}} - * and {{#crossLink "mouseChildren:property"}}{{/crossLink}} properties will be respected.
    • - *
    • Setting the `mode` to `2` additionally excludes display objects that do not have active mouse event - * listeners or a {{#crossLink "DisplayObject:cursor:property"}}{{/crossLink}} property. That is, only objects - * that would normally intercept mouse interaction will be included. This can significantly improve performance - * in some cases by reducing the number of display objects that need to be tested.
    • - * - * - * This method accounts for both {{#crossLink "DisplayObject/hitArea:property"}}{{/crossLink}} and {{#crossLink "DisplayObject/mask:property"}}{{/crossLink}}. - * @method getObjectsUnderPoint - * @param {Number} x The x position in the container to test. - * @param {Number} y The y position in the container to test. - * @param {Number} [mode=0] The mode to use to determine which display objects to include. 0-all, 1-respect mouseEnabled/mouseChildren, 2-only mouse opaque objects. - * @return {Array} An Array of DisplayObjects under the specified coordinates. + * Dispatched when an asynchronous build has progress. + * @event progress + * @param {Object} target The object that dispatched the event. + * @param {String} type The event type. + * @param {Number} progress The current progress value (0-1). + * @since 0.6.0 + */ + + +// public methods: + /** + * Adds a frame to the {{#crossLink "SpriteSheet"}}{{/crossLink}}. Note that the frame will not be drawn until you + * call {{#crossLink "SpriteSheetBuilder/build"}}{{/crossLink}} method. The optional setup params allow you to have + * a function run immediately before the draw occurs. For example, this allows you to add a single source multiple + * times, but manipulate it or its children to change it to generate different frames. + * + * Note that the source's transformations (x, y, scale, rotate, alpha) will be ignored, except for regX/Y. To apply + * transforms to a source object and have them captured in the SpriteSheet, simply place it into a {{#crossLink "Container"}}{{/crossLink}} + * and pass in the Container as the source. + * @method addFrame + * @param {DisplayObject} source The source {{#crossLink "DisplayObject"}}{{/crossLink}} to draw as the frame. + * @param {Rectangle} [sourceRect] A {{#crossLink "Rectangle"}}{{/crossLink}} defining the portion of the + * source to draw to the frame. If not specified, it will look for a `getBounds` method, bounds property, or + * `nominalBounds` property on the source to use. If one is not found, the frame will be skipped. + * @param {Number} [scale=1] Optional. The scale to draw this frame at. Default is 1. + * @param {Function} [setupFunction] A function to call immediately before drawing this frame. It will be called with two parameters: the source, and setupData. + * @param {Object} [setupData] Arbitrary setup data to pass to setupFunction as the second parameter. + * @return {Number} The index of the frame that was just added, or null if a sourceRect could not be determined. **/ - p.getObjectsUnderPoint = function(x, y, mode) { - var arr = []; - var pt = this.localToGlobal(x, y); - this._getObjectsUnderPoint(pt.x, pt.y, arr, mode>0, mode==1); - return arr; + p.addFrame = function(source, sourceRect, scale, setupFunction, setupData) { + if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } + var rect = sourceRect||source.bounds||source.nominalBounds; + if (!rect&&source.getBounds) { rect = source.getBounds(); } + if (!rect) { return null; } + scale = scale||1; + return this._frames.push({source:source, sourceRect:rect, scale:scale, funct:setupFunction, data:setupData, index:this._frames.length, height:rect.height*scale})-1; }; /** - * Similar to {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}}, but returns only the top-most display - * object. This runs significantly faster than getObjectsUnderPoint(), but is still potentially an expensive - * operation. See {{#crossLink "Container/getObjectsUnderPoint"}}{{/crossLink}} for more information. - * @method getObjectUnderPoint - * @param {Number} x The x position in the container to test. - * @param {Number} y The y position in the container to test. - * @param {Number} mode The mode to use to determine which display objects to include. 0-all, 1-respect mouseEnabled/mouseChildren, 2-only mouse opaque objects. - * @return {DisplayObject} The top-most display object under the specified coordinates. + * Adds an animation that will be included in the created {{#crossLink "SpriteSheet"}}{{/crossLink}}. + * @method addAnimation + * @param {String} name The name for the animation. + * @param {Array} frames An array of frame indexes that comprise the animation. Ex. [3,6,5] would describe an animation + * that played frame indexes 3, 6, and 5 in that order. + * @param {String} [next] Specifies the name of the animation to continue to after this animation ends. You can + * also pass false to have the animation stop when it ends. By default it will loop to the start of the same animation. + * @param {Number} [speed] Specifies a frame advance speed for this animation. For example, a value of 0.5 would + * cause the animation to advance every second tick. Note that earlier versions used `frequency` instead, which had + * the opposite effect. **/ - p.getObjectUnderPoint = function(x, y, mode) { - var pt = this.localToGlobal(x, y); - return this._getObjectsUnderPoint(pt.x, pt.y, null, mode>0, mode==1); + p.addAnimation = function(name, frames, next, speed) { + if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } + this._animations[name] = {frames:frames, next:next, speed:speed}; }; - + /** - * Docced in superclass. - */ - p.getBounds = function() { - return this._getBounds(null, true); + * This will take a {{#crossLink "MovieClip"}}{{/crossLink}} instance, and add its frames and labels to this + * builder. Labels will be added as an animation running from the label index to the next label. For example, if + * there is a label named "foo" at frame 0 and a label named "bar" at frame 10, in a MovieClip with 15 frames, it + * will add an animation named "foo" that runs from frame index 0 to 9, and an animation named "bar" that runs from + * frame index 10 to 14. + * + * Note that this will iterate through the full MovieClip with {{#crossLink "MovieClip/actionsEnabled:property"}}{{/crossLink}} + * set to `false`, ending on the last frame. + * @method addMovieClip + * @param {MovieClip} source The source MovieClip instance to add to the SpriteSheet. + * @param {Rectangle} [sourceRect] A {{#crossLink "Rectangle"}}{{/crossLink}} defining the portion of the source to + * draw to the frame. If not specified, it will look for a {{#crossLink "DisplayObject/getBounds"}}{{/crossLink}} + * method, `frameBounds` Array, `bounds` property, or `nominalBounds` property on the source to use. If one is not + * found, the MovieClip will be skipped. + * @param {Number} [scale=1] The scale to draw the movie clip at. + * @param {Function} [setupFunction] A function to call immediately before drawing each frame. It will be called + * with three parameters: the source, setupData, and the frame index. + * @param {Object} [setupData] Arbitrary setup data to pass to setupFunction as the second parameter. + * @param {Function} [labelFunction] This method will be called for each MovieClip label that is added with four + * parameters: the label name, the source MovieClip instance, the starting frame index (in the movieclip timeline) + * and the end index. It must return a new name for the label/animation, or `false` to exclude the label. + **/ + p.addMovieClip = function(source, sourceRect, scale, setupFunction, setupData, labelFunction) { + if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } + var rects = source.frameBounds; + var rect = sourceRect||source.bounds||source.nominalBounds; + if (!rect&&source.getBounds) { rect = source.getBounds(); } + if (!rect && !rects) { return; } + + var i, l, baseFrameIndex = this._frames.length; + var duration = source.timeline.duration; + for (i=0; i=0; i--) { - var child = this.children[i]; - if (child.tickEnabled && child._tick) { child._tick(evtObj); } + p._startBuild = function() { + var pad = this.padding||0; + this.progress = 0; + this.spriteSheet = null; + this._index = 0; + this._scale = this.scale; + var dataFrames = []; + this._data = { + images: [], + frames: dataFrames, + framerate: this.framerate, + animations: this._animations // TODO: should we "clone" _animations in case someone adds more animations after a build? + }; + + var frames = this._frames.slice(); + frames.sort(function(a,b) { return (a.height<=b.height) ? -1 : 1; }); + + if (frames[frames.length-1].height+pad*2 > this.maxHeight) { throw SpriteSheetBuilder.ERR_DIMENSIONS; } + var y=0, x=0; + var img = 0; + while (frames.length) { + var o = this._fillRow(frames, y, img, dataFrames, pad); + if (o.w > x) { x = o.w; } + y += o.h; + if (!o.h || !frames.length) { + var canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); + canvas.width = this._getSize(x,this.maxWidth); + canvas.height = this._getSize(y,this.maxHeight); + this._data.images[img] = canvas; + if (!o.h) { + x=y=0; + img++; + } } } - this.DisplayObject__tick(evtObj); }; /** - * Recursively clones all children of this container, and adds them to the target container. - * @method cloneChildren + * @method _setupMovieClipFrame * @protected - * @param {Container} o The target container. + * @return {Number} The width & height of the row. **/ - p._cloneChildren = function(o) { - if (o.children.length) { o.removeAllChildren(); } - var arr = o.children; - for (var i=0, l=this.children.length; i=0; i--) { + var frame = frames[i]; + var sc = this._scale*frame.scale; + var rect = frame.sourceRect; + var source = frame.source; + var rx = Math.floor(sc*rect.x-pad); + var ry = Math.floor(sc*rect.y-pad); + var rh = Math.ceil(sc*rect.height+pad*2); + var rw = Math.ceil(sc*rect.width+pad*2); + if (rw > w) { throw SpriteSheetBuilder.ERR_DIMENSIONS; } + if (rh > h || x+rw > w) { continue; } + frame.img = img; + frame.rect = new createjs.Rectangle(x,y,rw,rh); + height = height || rh; + frames.splice(i,1); + dataFrames[frame.index] = [x,y,rw,rh,img,Math.round(-rx+sc*source.regX-pad),Math.round(-ry+sc*source.regY-pad)]; + x += rw; + } + return {w:x, h:height}; + }; - // draw children one at a time, and check if we get a hit: - var children = this.children, l = children.length; - for (var i=l-1; i>=0; i--) { - var child = children[i]; - var hitArea = child.hitArea; - if (!child.visible || (!hitArea && !child.isVisible()) || (mouse && !child.mouseEnabled)) { continue; } - if (!hitArea && !this._testMask(child, x, y)) { continue; } - - // if a child container has a hitArea then we only need to check its hitArea, so we can treat it as a normal DO: - if (!hitArea && child instanceof Container) { - var result = child._getObjectsUnderPoint(x, y, arr, mouse, activeListener, currentDepth+1); - if (!arr && result) { return (mouse && !this.mouseChildren) ? this : result; } - } else { - if (mouse && !activeListener && !child._hasMouseEventListener()) { continue; } - - // TODO: can we pass displayProps forward, to avoid having to calculate this backwards every time? It's kind of a mixed bag. When we're only hunting for DOs with event listeners, it may not make sense. - var props = child.getConcatenatedDisplayProps(child._props); - mtx = props.matrix; - - if (hitArea) { - mtx.appendMatrix(hitArea.getMatrix(hitArea._props.matrix)); - props.alpha = hitArea.alpha; - } - - ctx.globalAlpha = props.alpha; - ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx-x, mtx.ty-y); - (hitArea||child).draw(ctx); - if (!this._testHit(ctx)) { continue; } - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.clearRect(0, 0, 2, 2); - if (arr) { arr.push(child); } - else { return (mouse && !this.mouseChildren) ? this : child; } - } + /** + * @method _endBuild + * @protected + **/ + p._endBuild = function() { + this.spriteSheet = new createjs.SpriteSheet(this._data); + this._data = null; + this.progress = 1; + this.dispatchEvent("complete"); + }; + + /** + * @method _run + * @protected + **/ + p._run = function() { + var ts = Math.max(0.01, Math.min(0.99, this.timeSlice||0.3))*50; + var t = (new Date()).getTime()+ts; + var complete = false; + while (t > (new Date()).getTime()) { + if (!this._drawNext()) { complete = true; break; } } - return null; + if (complete) { + this._endBuild(); + } else { + var _this = this; + this._timerID = setTimeout(function() { _this._run(); }, 50-ts); + } + var p = this.progress = this._index/this._frames.length; + if (this.hasEventListener("progress")) { + var evt = new createjs.Event("progress"); + evt.progress = p; + this.dispatchEvent(evt); + } + }; + + /** + * @method _drawNext + * @protected + * @return Boolean Returns false if this is the last draw. + **/ + p._drawNext = function() { + var frame = this._frames[this._index]; + var sc = frame.scale*this._scale; + var rect = frame.rect; + var sourceRect = frame.sourceRect; + var canvas = this._data.images[frame.img]; + var ctx = canvas.getContext("2d"); + frame.funct&&frame.funct(frame.source, frame.data); + ctx.save(); + ctx.beginPath(); + ctx.rect(rect.x, rect.y, rect.width, rect.height); + ctx.clip(); + ctx.translate(Math.ceil(rect.x-sourceRect.x*sc), Math.ceil(rect.y-sourceRect.y*sc)); + ctx.scale(sc,sc); + frame.source.draw(ctx); // display object will draw itself. + ctx.restore(); + return (++this._index) < this._frames.length; + }; + + + createjs.SpriteSheetBuilder = createjs.promote(SpriteSheetBuilder, "EventDispatcher"); +}()); + +//############################################################################## +// DOMElement.js +//############################################################################## + +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * This class is still experimental, and more advanced use is likely to be buggy. Please report bugs. + * + * A DOMElement allows you to associate a HTMLElement with the display list. It will be transformed + * within the DOM as though it is child of the {{#crossLink "Container"}}{{/crossLink}} it is added to. However, it is + * not rendered to canvas, and as such will retain whatever z-index it has relative to the canvas (ie. it will be + * drawn in front of or behind the canvas). + * + * The position of a DOMElement is relative to their parent node in the DOM. It is recommended that + * the DOM Object be added to a div that also contains the canvas so that they share the same position + * on the page. + * + * DOMElement is useful for positioning HTML elements over top of canvas content, and for elements + * that you want to display outside the bounds of the canvas. For example, a tooltip with rich HTML + * content. + * + *

      Mouse Interaction

      + * + * DOMElement instances are not full EaselJS display objects, and do not participate in EaselJS mouse + * events or support methods like hitTest. To get mouse events from a DOMElement, you must instead add handlers to + * the htmlElement (note, this does not support EventDispatcher) + * + * var domElement = new createjs.DOMElement(htmlElement); + * domElement.htmlElement.onclick = function() { + * console.log("clicked"); + * } + * + * @class DOMElement + * @extends DisplayObject + * @constructor + * @param {HTMLElement} htmlElement A reference or id for the DOM element to manage. + */ + function DOMElement(htmlElement) { + this.DisplayObject_constructor(); + + if (typeof(htmlElement)=="string") { htmlElement = document.getElementById(htmlElement); } + this.mouseEnabled = false; + + var style = htmlElement.style; + style.position = "absolute"; + style.transformOrigin = style.WebkitTransformOrigin = style.msTransformOrigin = style.MozTransformOrigin = style.OTransformOrigin = "0% 0%"; + + + // public properties: + /** + * The DOM object to manage. + * @property htmlElement + * @type HTMLElement + */ + this.htmlElement = htmlElement; + + + // private properties: + /** + * @property _oldMtx + * @type Matrix2D + * @protected + */ + this._oldProps = null; + } + var p = createjs.extend(DOMElement, createjs.DisplayObject); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** + * Returns true or false indicating whether the display object would be visible if drawn to a canvas. + * This does not account for whether it would be visible within the boundaries of the stage. + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method isVisible + * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas + */ + p.isVisible = function() { + return this.htmlElement != null; + }; + + /** + * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. + * Returns true if the draw was handled (useful for overriding functionality). + * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. + * @method draw + * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. + * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. + * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back + * into itself). + * @return {Boolean} + */ + p.draw = function(ctx, ignoreCache) { + // this relies on the _tick method because draw isn't called if the parent is not visible. + // the actual update happens in _handleDrawEnd + return true; + }; + + /** + * Not applicable to DOMElement. + * @method cache + */ + p.cache = function() {}; + + /** + * Not applicable to DOMElement. + * @method uncache + */ + p.uncache = function() {}; + + /** + * Not applicable to DOMElement. + * @method updateCache + */ + p.updateCache = function() {}; + + /** + * Not applicable to DOMElement. + * @method hitTest + */ + p.hitTest = function() {}; + + /** + * Not applicable to DOMElement. + * @method localToGlobal + */ + p.localToGlobal = function() {}; + + /** + * Not applicable to DOMElement. + * @method globalToLocal + */ + p.globalToLocal = function() {}; + + /** + * Not applicable to DOMElement. + * @method localToLocal + */ + p.localToLocal = function() {}; + + /** + * DOMElement cannot be cloned. Throws an error. + * @method clone + */ + p.clone = function() { + throw("DOMElement cannot be cloned.") }; - + /** - * @method _testMask - * @param {DisplayObject} target - * @param {Number} x - * @param {Number} y - * @return {Boolean} Indicates whether the x/y is within the masked region. + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + */ + p.toString = function() { + return "[DOMElement (name="+ this.name +")]"; + }; + + /** + * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances + * are not full EaselJS display objects and do not participate in EaselJS mouse events. + * @event click + */ + + /** + * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances + * are not full EaselJS display objects and do not participate in EaselJS mouse events. + * @event dblClick + */ + + /** + * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances + * are not full EaselJS display objects and do not participate in EaselJS mouse events. + * @event mousedown + */ + + /** + * The HTMLElement can listen for the mouseover event, not the DOMElement instance. + * Since DOMElement instances are not full EaselJS display objects and do not participate in EaselJS mouse events. + * @event mouseover + */ + + /** + * Not applicable to DOMElement. + * @event tick + */ + + +// private methods: + /** + * @method _tick + * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. + * function. * @protected - **/ - p._testMask = function(target, x, y) { - var mask = target.mask; - if (!mask || !mask.graphics || mask.graphics.isEmpty()) { return true; } - - var mtx = this._props.matrix, parent = target.parent; - mtx = parent ? parent.getConcatenatedMatrix(mtx) : mtx.identity(); - mtx = mask.getMatrix(mask._props.matrix).prependMatrix(mtx); - - var ctx = createjs.DisplayObject._hitTestContext; - ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx-x, mtx.ty-y); - - // draw the mask as a solid fill: - mask.graphics.drawAsPath(ctx); - ctx.fillStyle = "#000"; - ctx.fill(); - - if (!this._testHit(ctx)) { return false; } - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.clearRect(0, 0, 2, 2); - - return true; + */ + p._tick = function(evtObj) { + var stage = this.getStage(); + stage&&stage.on("drawend", this._handleDrawEnd, this, true); + this.DisplayObject__tick(evtObj); }; /** - * @method _getBounds - * @param {Matrix2D} matrix - * @param {Boolean} ignoreTransform If true, does not apply this object's transform. - * @return {Rectangle} + * @method _handleDrawEnd + * @param {Event} evt * @protected - **/ - p._getBounds = function(matrix, ignoreTransform) { - var bounds = this.DisplayObject_getBounds(); - if (bounds) { return this._transformBounds(bounds, matrix, ignoreTransform); } + */ + p._handleDrawEnd = function(evt) { + var o = this.htmlElement; + if (!o) { return; } + var style = o.style; - var mtx = this._props.matrix; - mtx = ignoreTransform ? mtx.identity() : this.getMatrix(mtx); - if (matrix) { mtx.prependMatrix(matrix); } + var props = this.getConcatenatedDisplayProps(this._props), mtx = props.matrix; - var l = this.children.length, rect=null; - for (var i=0; iExample - * This example creates a stage, adds a child to it, then uses {{#crossLink "Ticker"}}{{/crossLink}} to update the child - * and redraw the stage using {{#crossLink "Stage/update"}}{{/crossLink}}. - * - * var stage = new createjs.Stage("canvasElementId"); - * var image = new createjs.Bitmap("imagePath.png"); - * stage.addChild(image); - * createjs.Ticker.addEventListener("tick", handleTick); - * function handleTick(event) { - * image.x += 10; - * stage.update(); - * } - * - * @class Stage - * @extends Container - * @constructor - * @param {HTMLCanvasElement | String | Object} canvas A canvas object that the Stage will render to, or the string id - * of a canvas object in the current document. - **/ - function Stage(canvas) { - this.Container_constructor(); - - - // public properties: - /** - * Indicates whether the stage should automatically clear the canvas before each render. You can set this to false - * to manually control clearing (for generative art, or when pointing multiple stages at the same canvas for - * example). - * - *

      Example

      - * - * var stage = new createjs.Stage("canvasId"); - * stage.autoClear = false; - * - * @property autoClear - * @type Boolean - * @default true - **/ - this.autoClear = true; - - /** - * The canvas the stage will render to. Multiple stages can share a single canvas, but you must disable autoClear for all but the - * first stage that will be ticked (or they will clear each other's render). - * - * When changing the canvas property you must disable the events on the old canvas, and enable events on the - * new canvas or mouse events will not work as expected. For example: - * - * myStage.enableDOMEvents(false); - * myStage.canvas = anotherCanvas; - * myStage.enableDOMEvents(true); - * - * @property canvas - * @type HTMLCanvasElement | Object - **/ - this.canvas = (typeof canvas == "string") ? document.getElementById(canvas) : canvas; - - /** - * The current mouse X position on the canvas. If the mouse leaves the canvas, this will indicate the most recent - * position over the canvas, and mouseInBounds will be set to false. - * @property mouseX - * @type Number - * @readonly - **/ - this.mouseX = 0; - - /** - * The current mouse Y position on the canvas. If the mouse leaves the canvas, this will indicate the most recent - * position over the canvas, and mouseInBounds will be set to false. - * @property mouseY - * @type Number - * @readonly - **/ - this.mouseY = 0; - - /** - * Specifies the area of the stage to affect when calling update. This can be use to selectively - * re-draw specific regions of the canvas. If null, the whole canvas area is drawn. - * @property drawRect - * @type {Rectangle} - */ - this.drawRect = null; - - /** - * Indicates whether display objects should be rendered on whole pixels. You can set the - * {{#crossLink "DisplayObject/snapToPixel"}}{{/crossLink}} property of - * display objects to false to enable/disable this behaviour on a per instance basis. - * @property snapToPixelEnabled - * @type Boolean - * @default false - **/ - this.snapToPixelEnabled = false; - - /** - * Indicates whether the mouse is currently within the bounds of the canvas. - * @property mouseInBounds - * @type Boolean - * @default false - **/ - this.mouseInBounds = false; - - /** - * If true, tick callbacks will be called on all display objects on the stage prior to rendering to the canvas. - * @property tickOnUpdate - * @type Boolean - * @default true - **/ - this.tickOnUpdate = true; - - /** - * If true, mouse move events will continue to be called when the mouse leaves the target canvas. See - * {{#crossLink "Stage/mouseInBounds:property"}}{{/crossLink}}, and {{#crossLink "MouseEvent"}}{{/crossLink}} - * x/y/rawX/rawY. - * @property mouseMoveOutside - * @type Boolean - * @default false - **/ - this.mouseMoveOutside = false; - - - /** - * Prevents selection of other elements in the html page if the user clicks and drags, or double clicks on the canvas. - * This works by calling `preventDefault()` on any mousedown events (or touch equivalent) originating on the canvas. - * @property preventSelection - * @type Boolean - * @default true - **/ - this.preventSelection = true; - - /** - * The hitArea property is not supported for Stage. - * @property hitArea - * @type {DisplayObject} - * @default null - */ - - - // private properties: - /** - * Holds objects with data for each active pointer id. Each object has the following properties: - * x, y, event, target, overTarget, overX, overY, inBounds, posEvtObj (native event that last updated position) - * @property _pointerData - * @type {Object} - * @private - */ - this._pointerData = {}; - - /** - * Number of active pointers. - * @property _pointerCount - * @type {Object} - * @private - */ - this._pointerCount = 0; - - /** - * The ID of the primary pointer. - * @property _primaryPointerID - * @type {Object} - * @private - */ - this._primaryPointerID = null; - - /** - * @property _mouseOverIntervalID - * @protected - * @type Number - **/ - this._mouseOverIntervalID = null; - - /** - * @property _nextStage - * @protected - * @type Stage - **/ - this._nextStage = null; - - /** - * @property _prevStage - * @protected - * @type Stage - **/ - this._prevStage = null; - - - // initialize: - this.enableDOMEvents(true); - } - var p = createjs.extend(Stage, createjs.Container); - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// events: - /** - * Dispatched when the user moves the mouse over the canvas. - * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event stagemousemove - * @since 0.6.0 - */ - - /** - * Dispatched when the user presses their left mouse button on the canvas. See the {{#crossLink "MouseEvent"}}{{/crossLink}} - * class for a listing of event properties. - * @event stagemousedown - * @since 0.6.0 - */ - - /** - * Dispatched when the user the user presses somewhere on the stage, then releases the mouse button anywhere that the page can detect it (this varies slightly between browsers). - * You can use {{#crossLink "Stage/mouseInBounds:property"}}{{/crossLink}} to check whether the mouse is currently within the stage bounds. - * See the {{#crossLink "MouseEvent"}}{{/crossLink}} class for a listing of event properties. - * @event stagemouseup - * @since 0.6.0 - */ - - /** - * Dispatched when the mouse moves from within the canvas area (mouseInBounds == true) to outside it (mouseInBounds == false). - * This is currently only dispatched for mouse input (not touch). See the {{#crossLink "MouseEvent"}}{{/crossLink}} - * class for a listing of event properties. - * @event mouseleave - * @since 0.7.0 - */ - - /** - * Dispatched when the mouse moves into the canvas area (mouseInBounds == false) from outside it (mouseInBounds == true). - * This is currently only dispatched for mouse input (not touch). See the {{#crossLink "MouseEvent"}}{{/crossLink}} - * class for a listing of event properties. - * @event mouseenter - * @since 0.7.0 - */ - - /** - * Dispatched each update immediately before the tick event is propagated through the display list. - * You can call preventDefault on the event object to cancel propagating the tick event. - * @event tickstart - * @since 0.7.0 - */ - - /** - * Dispatched each update immediately after the tick event is propagated through the display list. Does not fire if - * tickOnUpdate is false. Precedes the "drawstart" event. - * @event tickend - * @since 0.7.0 - */ - - /** - * Dispatched each update immediately before the canvas is cleared and the display list is drawn to it. - * You can call preventDefault on the event object to cancel the draw. - * @event drawstart - * @since 0.7.0 - */ - - /** - * Dispatched each update immediately after the display list is drawn to the canvas and the canvas context is restored. - * @event drawend - * @since 0.7.0 - */ - - -// getter / setters: - /** - * Specifies a target stage that will have mouse / touch interactions relayed to it after this stage handles them. - * This can be useful in cases where you have multiple layered canvases and want user interactions - * events to pass through. For example, this would relay mouse events from topStage to bottomStage: - * - * topStage.nextStage = bottomStage; - * - * To disable relaying, set nextStage to null. - * - * MouseOver, MouseOut, RollOver, and RollOut interactions are also passed through using the mouse over settings - * of the top-most stage, but are only processed if the target stage has mouse over interactions enabled. - * Considerations when using roll over in relay targets:
        - *
      1. The top-most (first) stage must have mouse over interactions enabled (via enableMouseOver)
      2. - *
      3. All stages that wish to participate in mouse over interaction must enable them via enableMouseOver
      4. - *
      5. All relay targets will share the frequency value of the top-most stage
      6. - *
      - * To illustrate, in this example the targetStage would process mouse over interactions at 10hz (despite passing - * 30 as it's desired frequency): - * topStage.nextStage = targetStage; - * topStage.enableMouseOver(10); - * targetStage.enableMouseOver(30); - * - * If the target stage's canvas is completely covered by this stage's canvas, you may also want to disable its - * DOM events using: - * - * targetStage.enableDOMEvents(false); - * - * @property nextStage - * @type {Stage} - **/ - p._get_nextStage = function() { - return this._nextStage; - }; - p._set_nextStage = function(value) { - if (this._nextStage) { this._nextStage._prevStage = null; } - if (value) { value._prevStage = this; } - this._nextStage = value; - }; - - try { - Object.defineProperties(p, { - nextStage: { get: p._get_nextStage, set: p._set_nextStage } - }); - } catch (e) {} // TODO: use Log - - -// public methods: - /** - * Each time the update method is called, the stage will call {{#crossLink "Stage/tick"}}{{/crossLink}} - * unless {{#crossLink "Stage/tickOnUpdate:property"}}{{/crossLink}} is set to false, - * and then render the display list to the canvas. - * - * @method update - * @param {Object} [props] Props object to pass to `tick()`. Should usually be a {{#crossLink "Ticker"}}{{/crossLink}} event object, or similar object with a delta property. - **/ - p.update = function(props) { - if (!this.canvas) { return; } - if (this.tickOnUpdate) { this.tick(props); } - if (this.dispatchEvent("drawstart", false, true) === false) { return; } - createjs.DisplayObject._snapToPixelEnabled = this.snapToPixelEnabled; - var r = this.drawRect, ctx = this.canvas.getContext("2d"); - ctx.setTransform(1, 0, 0, 1, 0, 0); - if (this.autoClear) { - if (r) { ctx.clearRect(r.x, r.y, r.width, r.height); } - else { ctx.clearRect(0, 0, this.canvas.width+1, this.canvas.height+1); } - } - ctx.save(); - if (this.drawRect) { - ctx.beginPath(); - ctx.rect(r.x, r.y, r.width, r.height); - ctx.clip(); - } - this.updateContext(ctx); - this.draw(ctx, false); - ctx.restore(); - this.dispatchEvent("drawend"); - }; - - /** - * Propagates a tick event through the display list. This is automatically called by {{#crossLink "Stage/update"}}{{/crossLink}} - * unless {{#crossLink "Stage/tickOnUpdate:property"}}{{/crossLink}} is set to false. - * - * If a props object is passed to `tick()`, then all of its properties will be copied to the event object that is - * propagated to listeners. - * - * Some time-based features in EaselJS (for example {{#crossLink "Sprite/framerate"}}{{/crossLink}} require that - * a {{#crossLink "Ticker/tick:event"}}{{/crossLink}} event object (or equivalent object with a delta property) be - * passed as the `props` parameter to `tick()`. For example: - * - * Ticker.on("tick", handleTick); - * function handleTick(evtObj) { - * // clone the event object from Ticker, and add some custom data to it: - * var evt = evtObj.clone().set({greeting:"hello", name:"world"}); - * - * // pass it to stage.update(): - * myStage.update(evt); // subsequently calls tick() with the same param - * } - * - * // ... - * myDisplayObject.on("tick", handleDisplayObjectTick); - * function handleDisplayObjectTick(evt) { - * console.log(evt.delta); // the delta property from the Ticker tick event object - * console.log(evt.greeting, evt.name); // custom data: "hello world" - * } - * - * @method tick - * @param {Object} [props] An object with properties that should be copied to the event object. Should usually be a Ticker event object, or similar object with a delta property. - **/ - p.tick = function(props) { - if (!this.tickEnabled || this.dispatchEvent("tickstart", false, true) === false) { return; } - var evtObj = new createjs.Event("tick"); - if (props) { - for (var n in props) { - if (props.hasOwnProperty(n)) { evtObj[n] = props[n]; } - } - } - this._tick(evtObj); - this.dispatchEvent("tickend"); - }; - - /** - * Default event handler that calls the Stage {{#crossLink "Stage/update"}}{{/crossLink}} method when a {{#crossLink "DisplayObject/tick:event"}}{{/crossLink}} - * event is received. This allows you to register a Stage instance as a event listener on {{#crossLink "Ticker"}}{{/crossLink}} - * directly, using: - * - * Ticker.addEventListener("tick", myStage"); - * - * Note that if you subscribe to ticks using this pattern, then the tick event object will be passed through to - * display object tick handlers, instead of delta and paused parameters. - * @property handleEvent - * @type Function - **/ - p.handleEvent = function(evt) { - if (evt.type == "tick") { this.update(evt); } - }; - - /** - * Clears the target canvas. Useful if {{#crossLink "Stage/autoClear:property"}}{{/crossLink}} is set to `false`. - * @method clear - **/ - p.clear = function() { - if (!this.canvas) { return; } - var ctx = this.canvas.getContext("2d"); - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.clearRect(0, 0, this.canvas.width+1, this.canvas.height+1); - }; - - /** - * Returns a data url that contains a Base64-encoded image of the contents of the stage. The returned data url can - * be specified as the src value of an image element. - * @method toDataURL - * @param {String} [backgroundColor] The background color to be used for the generated image. Any valid CSS color - * value is allowed. The default value is a transparent background. - * @param {String} [mimeType="image/png"] The MIME type of the image format to be create. The default is "image/png". If an unknown MIME type - * is passed in, or if the browser does not support the specified MIME type, the default value will be used. - * @return {String} a Base64 encoded image. - **/ - p.toDataURL = function(backgroundColor, mimeType) { - var data, ctx = this.canvas.getContext('2d'), w = this.canvas.width, h = this.canvas.height; - - if (backgroundColor) { - data = ctx.getImageData(0, 0, w, h); - var compositeOperation = ctx.globalCompositeOperation; - ctx.globalCompositeOperation = "destination-over"; - - ctx.fillStyle = backgroundColor; - ctx.fillRect(0, 0, w, h); - } - - var dataURL = this.canvas.toDataURL(mimeType||"image/png"); - - if(backgroundColor) { - ctx.putImageData(data, 0, 0); - ctx.globalCompositeOperation = compositeOperation; - } - - return dataURL; - }; - - /** - * Enables or disables (by passing a frequency of 0) mouse over ({{#crossLink "DisplayObject/mouseover:event"}}{{/crossLink}} - * and {{#crossLink "DisplayObject/mouseout:event"}}{{/crossLink}}) and roll over events ({{#crossLink "DisplayObject/rollover:event"}}{{/crossLink}} - * and {{#crossLink "DisplayObject/rollout:event"}}{{/crossLink}}) for this stage's display list. These events can - * be expensive to generate, so they are disabled by default. The frequency of the events can be controlled - * independently of mouse move events via the optional `frequency` parameter. - * - *

      Example

      - * - * var stage = new createjs.Stage("canvasId"); - * stage.enableMouseOver(10); // 10 updates per second - * - * @method enableMouseOver - * @param {Number} [frequency=20] Optional param specifying the maximum number of times per second to broadcast - * mouse over/out events. Set to 0 to disable mouse over events completely. Maximum is 50. A lower frequency is less - * responsive, but uses less CPU. - **/ - p.enableMouseOver = function(frequency) { - if (this._mouseOverIntervalID) { - clearInterval(this._mouseOverIntervalID); - this._mouseOverIntervalID = null; - if (frequency == 0) { - this._testMouseOver(true); - } - } - if (frequency == null) { frequency = 20; } - else if (frequency <= 0) { return; } - var o = this; - this._mouseOverIntervalID = setInterval(function(){ o._testMouseOver(); }, 1000/Math.min(50,frequency)); - }; - - /** - * Enables or disables the event listeners that stage adds to DOM elements (window, document and canvas). It is good - * practice to disable events when disposing of a Stage instance, otherwise the stage will continue to receive - * events from the page. - * - * When changing the canvas property you must disable the events on the old canvas, and enable events on the - * new canvas or mouse events will not work as expected. For example: - * - * myStage.enableDOMEvents(false); - * myStage.canvas = anotherCanvas; - * myStage.enableDOMEvents(true); - * - * @method enableDOMEvents - * @param {Boolean} [enable=true] Indicates whether to enable or disable the events. Default is true. - **/ - p.enableDOMEvents = function(enable) { - if (enable == null) { enable = true; } - var n, o, ls = this._eventListeners; - if (!enable && ls) { - for (n in ls) { - o = ls[n]; - o.t.removeEventListener(n, o.f, false); - } - this._eventListeners = null; - } else if (enable && !ls && this.canvas) { - var t = window.addEventListener ? window : document; - var _this = this; - ls = this._eventListeners = {}; - ls["mouseup"] = {t:t, f:function(e) { _this._handleMouseUp(e)} }; - ls["mousemove"] = {t:t, f:function(e) { _this._handleMouseMove(e)} }; - ls["dblclick"] = {t:this.canvas, f:function(e) { _this._handleDoubleClick(e)} }; - ls["mousedown"] = {t:this.canvas, f:function(e) { _this._handleMouseDown(e)} }; - - for (n in ls) { - o = ls[n]; - o.t.addEventListener(n, o.f, false); - } - } - }; - - /** - * Stage instances cannot be cloned. - * @method clone - **/ - p.clone = function() { - throw("Stage cannot be cloned."); - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Stage (name="+ this.name +")]"; - }; - - -// private methods: - /** - * @method _getElementRect - * @protected - * @param {HTMLElement} e - **/ - p._getElementRect = function(e) { - var bounds; - try { bounds = e.getBoundingClientRect(); } // this can fail on disconnected DOM elements in IE9 - catch (err) { bounds = {top: e.offsetTop, left: e.offsetLeft, width:e.offsetWidth, height:e.offsetHeight}; } - - var offX = (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || document.body.clientLeft || 0); - var offY = (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || document.body.clientTop || 0); - - var styles = window.getComputedStyle ? getComputedStyle(e,null) : e.currentStyle; // IE <9 compatibility. - var padL = parseInt(styles.paddingLeft)+parseInt(styles.borderLeftWidth); - var padT = parseInt(styles.paddingTop)+parseInt(styles.borderTopWidth); - var padR = parseInt(styles.paddingRight)+parseInt(styles.borderRightWidth); - var padB = parseInt(styles.paddingBottom)+parseInt(styles.borderBottomWidth); - - // note: in some browsers bounds properties are read only. - return { - left: bounds.left+offX+padL, - right: bounds.right+offX-padR, - top: bounds.top+offY+padT, - bottom: bounds.bottom+offY-padB - } - }; - - /** - * @method _getPointerData - * @protected - * @param {Number} id - **/ - p._getPointerData = function(id) { - var data = this._pointerData[id]; - if (!data) { data = this._pointerData[id] = {x:0,y:0}; } - return data; - }; - - /** - * @method _handleMouseMove - * @protected - * @param {MouseEvent} e - **/ - p._handleMouseMove = function(e) { - if(!e){ e = window.event; } - this._handlePointerMove(-1, e, e.pageX, e.pageY); - }; - - /** - * @method _handlePointerMove - * @protected - * @param {Number} id - * @param {Event} e - * @param {Number} pageX - * @param {Number} pageY - * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. - **/ - p._handlePointerMove = function(id, e, pageX, pageY, owner) { - if (this._prevStage && owner === undefined) { return; } // redundant listener. - if (!this.canvas) { return; } - var nextStage=this._nextStage, o=this._getPointerData(id); - - var inBounds = o.inBounds; - this._updatePointerPosition(id, e, pageX, pageY); - if (inBounds || o.inBounds || this.mouseMoveOutside) { - if (id === -1 && o.inBounds == !inBounds) { - this._dispatchMouseEvent(this, (inBounds ? "mouseleave" : "mouseenter"), false, id, o, e); - } - - this._dispatchMouseEvent(this, "stagemousemove", false, id, o, e); - this._dispatchMouseEvent(o.target, "pressmove", true, id, o, e); - } - - nextStage&&nextStage._handlePointerMove(id, e, pageX, pageY, null); - }; - - /** - * @method _updatePointerPosition - * @protected - * @param {Number} id - * @param {Event} e - * @param {Number} pageX - * @param {Number} pageY - **/ - p._updatePointerPosition = function(id, e, pageX, pageY) { - var rect = this._getElementRect(this.canvas); - pageX -= rect.left; - pageY -= rect.top; - - var w = this.canvas.width; - var h = this.canvas.height; - pageX /= (rect.right-rect.left)/w; - pageY /= (rect.bottom-rect.top)/h; - var o = this._getPointerData(id); - if (o.inBounds = (pageX >= 0 && pageY >= 0 && pageX <= w-1 && pageY <= h-1)) { - o.x = pageX; - o.y = pageY; - } else if (this.mouseMoveOutside) { - o.x = pageX < 0 ? 0 : (pageX > w-1 ? w-1 : pageX); - o.y = pageY < 0 ? 0 : (pageY > h-1 ? h-1 : pageY); - } - - o.posEvtObj = e; - o.rawX = pageX; - o.rawY = pageY; - - if (id === this._primaryPointerID || id === -1) { - this.mouseX = o.x; - this.mouseY = o.y; - this.mouseInBounds = o.inBounds; - } - }; - - /** - * @method _handleMouseUp - * @protected - * @param {MouseEvent} e - **/ - p._handleMouseUp = function(e) { - this._handlePointerUp(-1, e, false); - }; - - /** - * @method _handlePointerUp - * @protected - * @param {Number} id - * @param {Event} e - * @param {Boolean} clear - * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. - **/ - p._handlePointerUp = function(id, e, clear, owner) { - var nextStage = this._nextStage, o = this._getPointerData(id); - if (this._prevStage && owner === undefined) { return; } // redundant listener. - - var target=null, oTarget = o.target; - if (!owner && (oTarget || nextStage)) { target = this._getObjectsUnderPoint(o.x, o.y, null, true); } - - if (o.down) { this._dispatchMouseEvent(this, "stagemouseup", false, id, o, e, target); o.down = false; } - - if (target == oTarget) { this._dispatchMouseEvent(oTarget, "click", true, id, o, e); } - this._dispatchMouseEvent(oTarget, "pressup", true, id, o, e); - - if (clear) { - if (id==this._primaryPointerID) { this._primaryPointerID = null; } - delete(this._pointerData[id]); - } else { o.target = null; } - - nextStage&&nextStage._handlePointerUp(id, e, clear, owner || target && this); - }; - - /** - * @method _handleMouseDown - * @protected - * @param {MouseEvent} e - **/ - p._handleMouseDown = function(e) { - this._handlePointerDown(-1, e, e.pageX, e.pageY); - }; - - /** - * @method _handlePointerDown - * @protected - * @param {Number} id - * @param {Event} e - * @param {Number} pageX - * @param {Number} pageY - * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. - **/ - p._handlePointerDown = function(id, e, pageX, pageY, owner) { - if (this.preventSelection) { e.preventDefault(); } - if (this._primaryPointerID == null || id === -1) { this._primaryPointerID = id; } // mouse always takes over. - - if (pageY != null) { this._updatePointerPosition(id, e, pageX, pageY); } - var target = null, nextStage = this._nextStage, o = this._getPointerData(id); - if (!owner) { target = o.target = this._getObjectsUnderPoint(o.x, o.y, null, true); } - - if (o.inBounds) { this._dispatchMouseEvent(this, "stagemousedown", false, id, o, e, target); o.down = true; } - this._dispatchMouseEvent(target, "mousedown", true, id, o, e); - - nextStage&&nextStage._handlePointerDown(id, e, pageX, pageY, owner || target && this); - }; - - /** - * @method _testMouseOver - * @param {Boolean} clear If true, clears the mouseover / rollover (ie. no target) - * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. - * @param {Stage} eventTarget The stage that the cursor is actively over. - * @protected - **/ - p._testMouseOver = function(clear, owner, eventTarget) { - if (this._prevStage && owner === undefined) { return; } // redundant listener. - - var nextStage = this._nextStage; - if (!this._mouseOverIntervalID) { - // not enabled for mouseover, but should still relay the event. - nextStage&&nextStage._testMouseOver(clear, owner, eventTarget); - return; - } - var o = this._getPointerData(-1); - // only update if the mouse position has changed. This provides a lot of optimization, but has some trade-offs. - if (!o || (!clear && this.mouseX == this._mouseOverX && this.mouseY == this._mouseOverY && this.mouseInBounds)) { return; } - - var e = o.posEvtObj; - var isEventTarget = eventTarget || e&&(e.target == this.canvas); - var target=null, common = -1, cursor="", t, i, l; - - if (!owner && (clear || this.mouseInBounds && isEventTarget)) { - target = this._getObjectsUnderPoint(this.mouseX, this.mouseY, null, true); - this._mouseOverX = this.mouseX; - this._mouseOverY = this.mouseY; - } - - var oldList = this._mouseOverTarget||[]; - var oldTarget = oldList[oldList.length-1]; - var list = this._mouseOverTarget = []; - - // generate ancestor list and check for cursor: - t = target; - while (t) { - list.unshift(t); - if (!cursor) { cursor = t.cursor; } - t = t.parent; - } - this.canvas.style.cursor = cursor; - if (!owner && eventTarget) { eventTarget.canvas.style.cursor = cursor; } - - // find common ancestor: - for (i=0,l=list.length; icommon; i--) { - this._dispatchMouseEvent(oldList[i], "rollout", false, -1, o, e, target); - } - - for (i=list.length-1; i>common; i--) { - this._dispatchMouseEvent(list[i], "rollover", false, -1, o, e, oldTarget); - } - - if (oldTarget != target) { - this._dispatchMouseEvent(target, "mouseover", true, -1, o, e, oldTarget); - } - - nextStage&&nextStage._testMouseOver(clear, owner || target && this, eventTarget || isEventTarget && this); - }; - - /** - * @method _handleDoubleClick - * @protected - * @param {MouseEvent} e - * @param {Stage} owner Indicates that the event has already been captured & handled by the indicated stage. - **/ - p._handleDoubleClick = function(e, owner) { - var target=null, nextStage=this._nextStage, o=this._getPointerData(-1); - if (!owner) { - target = this._getObjectsUnderPoint(o.x, o.y, null, true); - this._dispatchMouseEvent(target, "dblclick", true, -1, o, e); - } - nextStage&&nextStage._handleDoubleClick(e, owner || target && this); - }; - - /** - * @method _dispatchMouseEvent - * @protected - * @param {DisplayObject} target - * @param {String} type - * @param {Boolean} bubbles - * @param {Number} pointerId - * @param {Object} o - * @param {MouseEvent} [nativeEvent] - * @param {DisplayObject} [relatedTarget] - **/ - p._dispatchMouseEvent = function(target, type, bubbles, pointerId, o, nativeEvent, relatedTarget) { - // TODO: might be worth either reusing MouseEvent instances, or adding a willTrigger method to avoid GC. - if (!target || (!bubbles && !target.hasEventListener(type))) { return; } - /* - // TODO: account for stage transformations? - this._mtx = this.getConcatenatedMatrix(this._mtx).invert(); - var pt = this._mtx.transformPoint(o.x, o.y); - var evt = new createjs.MouseEvent(type, bubbles, false, pt.x, pt.y, nativeEvent, pointerId, pointerId==this._primaryPointerID || pointerId==-1, o.rawX, o.rawY); - */ - var evt = new createjs.MouseEvent(type, bubbles, false, o.x, o.y, nativeEvent, pointerId, pointerId === this._primaryPointerID || pointerId === -1, o.rawX, o.rawY, relatedTarget); - target.dispatchEvent(evt); - }; - - - createjs.Stage = createjs.promote(Stage, "Container"); -}()); - -//############################################################################## -// Bitmap.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - - /** - * A Bitmap represents an Image, Canvas, or Video in the display list. A Bitmap can be instantiated using an existing - * HTML element, or a string. - * - *

      Example

      - * - * var bitmap = new createjs.Bitmap("imagePath.jpg"); - * - * Notes: - *
        - *
      1. When a string path or image tag that is not yet loaded is used, the stage may need to be redrawn before it - * will be displayed.
      2. - *
      3. Bitmaps with an SVG source currently will not respect an alpha value other than 0 or 1. To get around this, - * the Bitmap can be cached.
      4. - *
      5. Bitmaps with an SVG source will taint the canvas with cross-origin data, which prevents interactivity. This - * happens in all browsers except recent Firefox builds.
      6. - *
      7. Images loaded cross-origin will throw cross-origin security errors when interacted with using a mouse, using - * methods such as `getObjectUnderPoint`, or using filters, or caching. You can get around this by setting - * `crossOrigin` flags on your images before passing them to EaselJS, eg: `img.crossOrigin="Anonymous";`
      8. - *
      - * - * @class Bitmap - * @extends DisplayObject - * @constructor - * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | String} imageOrUri The source object or URI to an image to - * display. This can be either an Image, Canvas, or Video object, or a string URI to an image file to load and use. - * If it is a URI, a new Image object will be constructed and assigned to the .image property. - **/ - function Bitmap(imageOrUri) { - this.DisplayObject_constructor(); - - - // public properties: - /** - * The image to render. This can be an Image, a Canvas, or a Video. Not all browsers (especially - * mobile browsers) support drawing video to a canvas. - * @property image - * @type HTMLImageElement | HTMLCanvasElement | HTMLVideoElement - **/ - if (typeof imageOrUri == "string") { - this.image = document.createElement("img"); - this.image.src = imageOrUri; - } else { - this.image = imageOrUri; - } - - /** - * Specifies an area of the source image to draw. If omitted, the whole image will be drawn. - * Note that video sources must have a width / height set to work correctly with `sourceRect`. - * @property sourceRect - * @type Rectangle - * @default null - */ - this.sourceRect = null; - } - var p = createjs.extend(Bitmap, createjs.DisplayObject); - - -// public methods: - /** - * Constructor alias for backwards compatibility. This method will be removed in future versions. - * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. - * @method initialize - * @deprecated in favour of `createjs.promote()` - **/ - p.initialize = Bitmap; // TODO: deprecated. - - /** - * Returns true or false indicating whether the display object would be visible if drawn to a canvas. - * This does not account for whether it would be visible within the boundaries of the stage. - * - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method isVisible - * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas - **/ - p.isVisible = function() { - var image = this.image; - var hasContent = this.cacheCanvas || (image && (image.naturalWidth || image.getContext || image.readyState >= 2)); - return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); - }; - - /** - * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. - * Returns true if the draw was handled (useful for overriding functionality). - * - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method draw - * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. - * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back - * into itself). - * @return {Boolean} - **/ - p.draw = function(ctx, ignoreCache) { - if (this.DisplayObject_draw(ctx, ignoreCache) || !this.image) { return true; } - var img = this.image, rect = this.sourceRect; - if (rect) { - // some browsers choke on out of bound values, so we'll fix them: - var x1 = rect.x, y1 = rect.y, x2 = x1 + rect.width, y2 = y1 + rect.height, x = 0, y = 0, w = img.width, h = img.height; - if (x1 < 0) { x -= x1; x1 = 0; } - if (x2 > w) { x2 = w; } - if (y1 < 0) { y -= y1; y1 = 0; } - if (y2 > h) { y2 = h; } - ctx.drawImage(img, x1, y1, x2-x1, y2-y1, x, y, x2-x1, y2-y1); - } else { - ctx.drawImage(img, 0, 0); - } - return true; - }; - - //Note, the doc sections below document using the specified APIs (from DisplayObject) from - //Bitmap. This is why they have no method implementations. - - /** - * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. - * You should not cache Bitmap instances as it can degrade performance. - * - * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. - * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} - * method. - * @method cache - **/ - - /** - * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. - * You should not cache Bitmap instances as it can degrade performance. - * - * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. - * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} - * method. - * @method updateCache - **/ - - /** - * Because the content of a Bitmap is already in a simple format, cache is unnecessary for Bitmap instances. - * You should not cache Bitmap instances as it can degrade performance. - * - * However: If you want to use a filter on a Bitmap, you MUST cache it, or it will not work. - * To see the API for caching, please visit the DisplayObject {{#crossLink "DisplayObject/cache"}}{{/crossLink}} - * method. - * @method uncache - **/ - - /** - * Docced in superclass. - */ - p.getBounds = function() { - var rect = this.DisplayObject_getBounds(); - if (rect) { return rect; } - var image = this.image, o = this.sourceRect || image; - var hasContent = (image && (image.naturalWidth || image.getContext || image.readyState >= 2)); - return hasContent ? this._rectangle.setValues(0, 0, o.width, o.height) : null; - }; - - /** - * Returns a clone of the Bitmap instance. - * @method clone - * @return {Bitmap} a clone of the Bitmap instance. - **/ - p.clone = function() { - var o = new Bitmap(this.image); - if (this.sourceRect) { o.sourceRect = this.sourceRect.clone(); } - this._cloneProps(o); - return o; - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Bitmap (name="+ this.name +")]"; - }; - - - createjs.Bitmap = createjs.promote(Bitmap, "DisplayObject"); -}()); - -//############################################################################## -// Sprite.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Displays a frame or sequence of frames (ie. an animation) from a SpriteSheet instance. A sprite sheet is a series of - * images (usually animation frames) combined into a single image. For example, an animation consisting of 8 100x100 - * images could be combined into a 400x200 sprite sheet (4 frames across by 2 high). You can display individual frames, - * play frames as an animation, and even sequence animations together. - * - * See the {{#crossLink "SpriteSheet"}}{{/crossLink}} class for more information on setting up frames and animations. - * - *

      Example

      - * - * var instance = new createjs.Sprite(spriteSheet); - * instance.gotoAndStop("frameName"); - * - * Until {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} or {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} is called, - * only the first defined frame defined in the sprite sheet will be displayed. - * - * @class Sprite - * @extends DisplayObject - * @constructor - * @param {SpriteSheet} spriteSheet The SpriteSheet instance to play back. This includes the source image(s), frame - * dimensions, and frame data. See {{#crossLink "SpriteSheet"}}{{/crossLink}} for more information. - * @param {String|Number} [frameOrAnimation] The frame number or animation to play initially. - **/ - function Sprite(spriteSheet, frameOrAnimation) { - this.DisplayObject_constructor(); - - - // public properties: - /** - * The frame index that will be drawn when draw is called. Note that with some {{#crossLink "SpriteSheet"}}{{/crossLink}} - * definitions, this will advance non-sequentially. This will always be an integer value. - * @property currentFrame - * @type {Number} - * @default 0 - * @readonly - **/ - this.currentFrame = 0; - - /** - * Returns the name of the currently playing animation. - * @property currentAnimation - * @type {String} - * @final - * @readonly - **/ - this.currentAnimation = null; - - /** - * Prevents the animation from advancing each tick automatically. For example, you could create a sprite - * sheet of icons, set paused to true, and display the appropriate icon by setting currentFrame. - * @property paused - * @type {Boolean} - * @default false - **/ - this.paused = true; - - /** - * The SpriteSheet instance to play back. This includes the source image, frame dimensions, and frame - * data. See {{#crossLink "SpriteSheet"}}{{/crossLink}} for more information. - * @property spriteSheet - * @type {SpriteSheet} - * @readonly - **/ - this.spriteSheet = spriteSheet; - - /** - * Specifies the current frame index within the currently playing animation. When playing normally, this will increase - * from 0 to n-1, where n is the number of frames in the current animation. - * - * This could be a non-integer value if - * using time-based playback (see {{#crossLink "Sprite/framerate"}}{{/crossLink}}, or if the animation's speed is - * not an integer. - * @property currentAnimationFrame - * @type {Number} - * @default 0 - **/ - this.currentAnimationFrame = 0; - - /** - * By default Sprite instances advance one frame per tick. Specifying a framerate for the Sprite (or its related - * SpriteSheet) will cause it to advance based on elapsed time between ticks as appropriate to maintain the target - * framerate. - * - * For example, if a Sprite with a framerate of 10 is placed on a Stage being updated at 40fps, then the Sprite will - * advance roughly one frame every 4 ticks. This will not be exact, because the time between each tick will - * vary slightly between frames. - * - * This feature is dependent on the tick event object (or an object with an appropriate "delta" property) being - * passed into {{#crossLink "Stage/update"}}{{/crossLink}}. - * @property framerate - * @type {Number} - * @default 0 - **/ - this.framerate = 0; - - - // private properties: - /** - * Current animation object. - * @property _animation - * @protected - * @type {Object} - * @default null - **/ - this._animation = null; - - /** - * Current frame index. - * @property _currentFrame - * @protected - * @type {Number} - * @default null - **/ - this._currentFrame = null; - - /** - * Skips the next auto advance. Used by gotoAndPlay to avoid immediately jumping to the next frame - * @property _skipAdvance - * @protected - * @type {Boolean} - * @default false - **/ - this._skipAdvance = false; - - - if (frameOrAnimation != null) { this.gotoAndPlay(frameOrAnimation); } - } - var p = createjs.extend(Sprite, createjs.DisplayObject); - - /** - * Constructor alias for backwards compatibility. This method will be removed in future versions. - * Subclasses should be updated to use {{#crossLink "Utility Methods/extends"}}{{/crossLink}}. - * @method initialize - * @deprecated in favour of `createjs.promote()` - **/ - p.initialize = Sprite; // TODO: Deprecated. This is for backwards support of FlashCC spritesheet export. - - -// events: - /** - * Dispatched when an animation reaches its ends. - * @event animationend - * @param {Object} target The object that dispatched the event. - * @param {String} type The event type. - * @param {String} name The name of the animation that just ended. - * @param {String} next The name of the next animation that will be played, or null. This will be the same as name if the animation is looping. - * @since 0.6.0 - */ - - /** - * Dispatched any time the current frame changes. For example, this could be due to automatic advancement on a tick, - * or calling gotoAndPlay() or gotoAndStop(). - * @event change - * @param {Object} target The object that dispatched the event. - * @param {String} type The event type. - */ - - -// public methods: - /** - * Returns true or false indicating whether the display object would be visible if drawn to a canvas. - * This does not account for whether it would be visible within the boundaries of the stage. - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method isVisible - * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas - **/ - p.isVisible = function() { - var hasContent = this.cacheCanvas || this.spriteSheet.complete; - return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); - }; - - /** - * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. - * Returns true if the draw was handled (useful for overriding functionality). - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method draw - * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. - * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back - * into itself). - **/ - p.draw = function(ctx, ignoreCache) { - if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } - this._normalizeFrame(); - var o = this.spriteSheet.getFrame(this._currentFrame|0); - if (!o) { return false; } - var rect = o.rect; - if (rect.width && rect.height) { ctx.drawImage(o.image, rect.x, rect.y, rect.width, rect.height, -o.regX, -o.regY, rect.width, rect.height); } - return true; - }; - - //Note, the doc sections below document using the specified APIs (from DisplayObject) from - //Bitmap. This is why they have no method implementations. - - /** - * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. - * You should not cache Sprite instances as it can degrade performance. - * @method cache - **/ - - /** - * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. - * You should not cache Sprite instances as it can degrade performance. - * @method updateCache - **/ - - /** - * Because the content of a Sprite is already in a raster format, cache is unnecessary for Sprite instances. - * You should not cache Sprite instances as it can degrade performance. - * @method uncache - **/ - - /** - * Play (unpause) the current animation. The Sprite will be paused if either {{#crossLink "Sprite/stop"}}{{/crossLink}} - * or {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} is called. Single frame animations will remain - * unchanged. - * @method play - **/ - p.play = function() { - this.paused = false; - }; - - /** - * Stop playing a running animation. The Sprite will be playing if {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} - * is called. Note that calling {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}} or {{#crossLink "Sprite/play"}}{{/crossLink}} - * will resume playback. - * @method stop - **/ - p.stop = function() { - this.paused = true; - }; - - /** - * Sets paused to false and plays the specified animation name, named frame, or frame number. - * @method gotoAndPlay - * @param {String|Number} frameOrAnimation The frame number or animation name that the playhead should move to - * and begin playing. - **/ - p.gotoAndPlay = function(frameOrAnimation) { - this.paused = false; - this._skipAdvance = true; - this._goto(frameOrAnimation); - }; - - /** - * Sets paused to true and seeks to the specified animation name, named frame, or frame number. - * @method gotoAndStop - * @param {String|Number} frameOrAnimation The frame number or animation name that the playhead should move to - * and stop. - **/ - p.gotoAndStop = function(frameOrAnimation) { - this.paused = true; - this._goto(frameOrAnimation); - }; - - /** - * Advances the playhead. This occurs automatically each tick by default. - * @param [time] {Number} The amount of time in ms to advance by. Only applicable if framerate is set on the Sprite - * or its SpriteSheet. - * @method advance - */ - p.advance = function(time) { - var fps = this.framerate || this.spriteSheet.framerate; - var t = (fps && time != null) ? time/(1000/fps) : 1; - this._normalizeFrame(t); - }; - - /** - * Returns a {{#crossLink "Rectangle"}}{{/crossLink}} instance defining the bounds of the current frame relative to - * the origin. For example, a 90 x 70 frame with regX=50 and regY=40 would return a - * rectangle with [x=-50, y=-40, width=90, height=70]. This ignores transformations on the display object. - * - * Also see the SpriteSheet {{#crossLink "SpriteSheet/getFrameBounds"}}{{/crossLink}} method. - * @method getBounds - * @return {Rectangle} A Rectangle instance. Returns null if the frame does not exist, or the image is not fully - * loaded. - **/ - p.getBounds = function() { - // TODO: should this normalizeFrame? - return this.DisplayObject_getBounds() || this.spriteSheet.getFrameBounds(this.currentFrame, this._rectangle); - }; - - /** - * Returns a clone of the Sprite instance. Note that the same SpriteSheet is shared between cloned - * instances. - * @method clone - * @return {Sprite} a clone of the Sprite instance. - **/ - p.clone = function() { - return this._cloneProps(new Sprite(this.spriteSheet)); - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Sprite (name="+ this.name +")]"; - }; - -// private methods: - /** - * @method _cloneProps - * @param {Sprite} o - * @return {Sprite} o - * @protected - **/ - p._cloneProps = function(o) { - this.DisplayObject__cloneProps(o); - o.currentFrame = this.currentFrame; - o.currentAnimation = this.currentAnimation; - o.paused = this.paused; - o.currentAnimationFrame = this.currentAnimationFrame; - o.framerate = this.framerate; - - o._animation = this._animation; - o._currentFrame = this._currentFrame; - o._skipAdvance = this._skipAdvance; - return o; - }; - - /** - * Advances the currentFrame if paused is not true. This is called automatically when the {{#crossLink "Stage"}}{{/crossLink}} - * ticks. - * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. - * @protected - * @method _tick - **/ - p._tick = function(evtObj) { - if (!this.paused) { - if (!this._skipAdvance) { this.advance(evtObj&&evtObj.delta); } - this._skipAdvance = false; - } - this.DisplayObject__tick(evtObj); - }; - - - /** - * Normalizes the current frame, advancing animations and dispatching callbacks as appropriate. - * @protected - * @method _normalizeFrame - **/ - p._normalizeFrame = function(frameDelta) { - frameDelta = frameDelta || 0; - var animation = this._animation; - var paused = this.paused; - var frame = this._currentFrame; - var l; - - if (animation) { - var speed = animation.speed || 1; - var animFrame = this.currentAnimationFrame; - l = animation.frames.length; - if (animFrame + frameDelta * speed >= l) { - var next = animation.next; - if (this._dispatchAnimationEnd(animation, frame, paused, next, l - 1)) { - // something changed in the event stack, so we shouldn't make any more changes here. - return; - } else if (next) { - // sequence. Automatically calls _normalizeFrame again with the remaining frames. - return this._goto(next, frameDelta - (l - animFrame) / speed); - } else { - // end. - this.paused = true; - animFrame = animation.frames.length - 1; - } - } else { - animFrame += frameDelta * speed; - } - this.currentAnimationFrame = animFrame; - this._currentFrame = animation.frames[animFrame | 0] - } else { - frame = (this._currentFrame += frameDelta); - l = this.spriteSheet.getNumFrames(); - if (frame >= l && l > 0) { - if (!this._dispatchAnimationEnd(animation, frame, paused, l - 1)) { - // looped. - if ((this._currentFrame -= l) >= l) { return this._normalizeFrame(); } - } - } - } - frame = this._currentFrame | 0; - if (this.currentFrame != frame) { - this.currentFrame = frame; - this.dispatchEvent("change"); - } - }; - - /** - * Dispatches the "animationend" event. Returns true if a handler changed the animation (ex. calling {{#crossLink "Sprite/stop"}}{{/crossLink}}, - * {{#crossLink "Sprite/gotoAndPlay"}}{{/crossLink}}, etc.) - * @property _dispatchAnimationEnd - * @private - * @type {Function} - **/ - p._dispatchAnimationEnd = function(animation, frame, paused, next, end) { - var name = animation ? animation.name : null; - if (this.hasEventListener("animationend")) { - var evt = new createjs.Event("animationend"); - evt.name = name; - evt.next = next; - this.dispatchEvent(evt); - } - // did the animation get changed in the event stack?: - var changed = (this._animation != animation || this._currentFrame != frame); - // if the animation hasn't changed, but the sprite was paused, then we want to stick to the last frame: - if (!changed && !paused && this.paused) { this.currentAnimationFrame = end; changed = true; } - return changed; - }; - - /** - * Moves the playhead to the specified frame number or animation. - * @method _goto - * @param {String|Number} frameOrAnimation The frame number or animation that the playhead should move to. - * @param {Boolean} [frame] The frame of the animation to go to. Defaults to 0. - * @protected - **/ - p._goto = function(frameOrAnimation, frame) { - this.currentAnimationFrame = 0; - if (isNaN(frameOrAnimation)) { - var data = this.spriteSheet.getAnimation(frameOrAnimation); - if (data) { - this._animation = data; - this.currentAnimation = frameOrAnimation; - this._normalizeFrame(frame); - } - } else { - this.currentAnimation = this._animation = null; - this._currentFrame = frameOrAnimation; - this._normalizeFrame(); - } - }; - - - createjs.Sprite = createjs.promote(Sprite, "DisplayObject"); -}()); - -//############################################################################## -// Shape.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * A Shape allows you to display vector art in the display list. It composites a {{#crossLink "Graphics"}}{{/crossLink}} - * instance which exposes all of the vector drawing methods. The Graphics instance can be shared between multiple Shape - * instances to display the same vector graphics with different positions or transforms. - * - * If the vector art will not - * change between draws, you may want to use the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method to reduce the - * rendering cost. - * - *

      Example

      - * - * var graphics = new createjs.Graphics().beginFill("#ff0000").drawRect(0, 0, 100, 100); - * var shape = new createjs.Shape(graphics); - * - * //Alternatively use can also use the graphics property of the Shape class to renderer the same as above. - * var shape = new createjs.Shape(); - * shape.graphics.beginFill("#ff0000").drawRect(0, 0, 100, 100); - * - * @class Shape - * @extends DisplayObject - * @constructor - * @param {Graphics} graphics Optional. The graphics instance to display. If null, a new Graphics instance will be created. - **/ - function Shape(graphics) { - this.DisplayObject_constructor(); - - - // public properties: - /** - * The graphics instance to display. - * @property graphics - * @type Graphics - **/ - this.graphics = graphics ? graphics : new createjs.Graphics(); - } - var p = createjs.extend(Shape, createjs.DisplayObject); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// public methods: - /** - * Returns true or false indicating whether the Shape would be visible if drawn to a canvas. - * This does not account for whether it would be visible within the boundaries of the stage. - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method isVisible - * @return {Boolean} Boolean indicating whether the Shape would be visible if drawn to a canvas - **/ - p.isVisible = function() { - var hasContent = this.cacheCanvas || (this.graphics && !this.graphics.isEmpty()); - return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); - }; - - /** - * Draws the Shape into the specified context ignoring its visible, alpha, shadow, and transform. Returns true if - * the draw was handled (useful for overriding functionality). - * - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method draw - * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - * @param {Boolean} [ignoreCache=false] Indicates whether the draw operation should ignore any current cache. For example, - * used for drawing the cache (to prevent it from simply drawing an existing cache back into itself). - * @return {Boolean} - **/ - p.draw = function(ctx, ignoreCache) { - if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } - this.graphics.draw(ctx, this); - return true; - }; - - /** - * Returns a clone of this Shape. Some properties that are specific to this instance's current context are reverted to - * their defaults (for example .parent). - * @method clone - * @param {Boolean} recursive If true, this Shape's {{#crossLink "Graphics"}}{{/crossLink}} instance will also be - * cloned. If false, the Graphics instance will be shared with the new Shape. - **/ - p.clone = function(recursive) { - var g = (recursive && this.graphics) ? this.graphics.clone() : this.graphics; - return this._cloneProps(new Shape(g)); - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Shape (name="+ this.name +")]"; - }; - - - createjs.Shape = createjs.promote(Shape, "DisplayObject"); -}()); - -//############################################################################## -// Text.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Display one or more lines of dynamic text (not user editable) in the display list. Line wrapping support (using the - * lineWidth) is very basic, wrapping on spaces and tabs only. Note that as an alternative to Text, you can position HTML - * text above or below the canvas relative to items in the display list using the {{#crossLink "DisplayObject/localToGlobal"}}{{/crossLink}} - * method, or using {{#crossLink "DOMElement"}}{{/crossLink}}. - * - * Please note that Text does not support HTML text, and can only display one font style at a time. To use - * multiple font styles, you will need to create multiple text instances, and position them manually. - * - *

      Example

      - * - * var text = new createjs.Text("Hello World", "20px Arial", "#ff7700"); - * text.x = 100; - * text.textBaseline = "alphabetic"; - * - * CreateJS Text supports web fonts (the same rules as Canvas). The font must be loaded and supported by the browser - * before it can be displayed. - * - * Note: Text can be expensive to generate, so cache instances where possible. Be aware that not all - * browsers will render Text exactly the same. - * @class Text - * @extends DisplayObject - * @constructor - * @param {String} [text] The text to display. - * @param {String} [font] The font style to use. Any valid value for the CSS font attribute is acceptable (ex. "bold - * 36px Arial"). - * @param {String} [color] The color to draw the text in. Any valid value for the CSS color attribute is acceptable (ex. - * "#F00", "red", or "#FF0000"). - **/ - function Text(text, font, color) { - this.DisplayObject_constructor(); - - - // public properties: - /** - * The text to display. - * @property text - * @type String - **/ - this.text = text; - - /** - * The font style to use. Any valid value for the CSS font attribute is acceptable (ex. "bold 36px Arial"). - * @property font - * @type String - **/ - this.font = font; - - /** - * The color to draw the text in. Any valid value for the CSS color attribute is acceptable (ex. "#F00"). Default is "#000". - * It will also accept valid canvas fillStyle values. - * @property color - * @type String - **/ - this.color = color; - - /** - * The horizontal text alignment. Any of "start", "end", "left", "right", and "center". For detailed - * information view the - * - * whatwg spec. Default is "left". - * @property textAlign - * @type String - **/ - this.textAlign = "left"; - - /** - * The vertical alignment point on the font. Any of "top", "hanging", "middle", "alphabetic", "ideographic", or - * "bottom". For detailed information view the - * whatwg spec. Default is "top". - * @property textBaseline - * @type String - */ - this.textBaseline = "top"; - - /** - * The maximum width to draw the text. If maxWidth is specified (not null), the text will be condensed or - * shrunk to make it fit in this width. For detailed information view the - * - * whatwg spec. - * @property maxWidth - * @type Number - */ - this.maxWidth = null; - - /** - * If greater than 0, the text will be drawn as a stroke (outline) of the specified width. - * @property outline - * @type Number - **/ - this.outline = 0; - - /** - * Indicates the line height (vertical distance between baselines) for multi-line text. If null or 0, - * the value of getMeasuredLineHeight is used. - * @property lineHeight - * @type Number - **/ - this.lineHeight = 0; - - /** - * Indicates the maximum width for a line of text before it is wrapped to multiple lines. If null, - * the text will not be wrapped. - * @property lineWidth - * @type Number - **/ - this.lineWidth = null; - } - var p = createjs.extend(Text, createjs.DisplayObject); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// static properties: - /** - * @property _workingContext - * @type CanvasRenderingContext2D - * @private - **/ - var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); - if (canvas.getContext) { Text._workingContext = canvas.getContext("2d"); canvas.width = canvas.height = 1; } - - -// constants: - /** - * Lookup table for the ratio to offset bounds x calculations based on the textAlign property. - * @property H_OFFSETS - * @type Object - * @protected - * @static - **/ - Text.H_OFFSETS = {start: 0, left: 0, center: -0.5, end: -1, right: -1}; - - /** - * Lookup table for the ratio to offset bounds y calculations based on the textBaseline property. - * @property H_OFFSETS - * @type Object - * @protected - * @static - **/ - Text.V_OFFSETS = {top: 0, hanging: -0.01, middle: -0.4, alphabetic: -0.8, ideographic: -0.85, bottom: -1}; - - -// public methods: - /** - * Returns true or false indicating whether the display object would be visible if drawn to a canvas. - * This does not account for whether it would be visible within the boundaries of the stage. - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method isVisible - * @return {Boolean} Whether the display object would be visible if drawn to a canvas - **/ - p.isVisible = function() { - var hasContent = this.cacheCanvas || (this.text != null && this.text !== ""); - return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0 && hasContent); - }; - - /** - * Draws the Text into the specified context ignoring its visible, alpha, shadow, and transform. - * Returns true if the draw was handled (useful for overriding functionality). - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method draw - * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. - * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back - * into itself). - **/ - p.draw = function(ctx, ignoreCache) { - if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; } - - var col = this.color || "#000"; - if (this.outline) { ctx.strokeStyle = col; ctx.lineWidth = this.outline*1; } - else { ctx.fillStyle = col; } - - this._drawText(this._prepContext(ctx)); - return true; - }; - - /** - * Returns the measured, untransformed width of the text without wrapping. Use getBounds for a more robust value. - * @method getMeasuredWidth - * @return {Number} The measured, untransformed width of the text. - **/ - p.getMeasuredWidth = function() { - return this._getMeasuredWidth(this.text); - }; - - /** - * Returns an approximate line height of the text, ignoring the lineHeight property. This is based on the measured - * width of a "M" character multiplied by 1.2, which provides an approximate line height for most fonts. - * @method getMeasuredLineHeight - * @return {Number} an approximate line height of the text, ignoring the lineHeight property. This is - * based on the measured width of a "M" character multiplied by 1.2, which approximates em for most fonts. - **/ - p.getMeasuredLineHeight = function() { - return this._getMeasuredWidth("M")*1.2; - }; - - /** - * Returns the approximate height of multi-line text by multiplying the number of lines against either the - * lineHeight (if specified) or {{#crossLink "Text/getMeasuredLineHeight"}}{{/crossLink}}. Note that - * this operation requires the text flowing logic to run, which has an associated CPU cost. - * @method getMeasuredHeight - * @return {Number} The approximate height of the untransformed multi-line text. - **/ - p.getMeasuredHeight = function() { - return this._drawText(null,{}).height; - }; - - /** - * Docced in superclass. - */ - p.getBounds = function() { - var rect = this.DisplayObject_getBounds(); - if (rect) { return rect; } - if (this.text == null || this.text === "") { return null; } - var o = this._drawText(null, {}); - var w = (this.maxWidth && this.maxWidth < o.width) ? this.maxWidth : o.width; - var x = w * Text.H_OFFSETS[this.textAlign||"left"]; - var lineHeight = this.lineHeight||this.getMeasuredLineHeight(); - var y = lineHeight * Text.V_OFFSETS[this.textBaseline||"top"]; - return this._rectangle.setValues(x, y, w, o.height); - }; - - /** - * Returns an object with width, height, and lines properties. The width and height are the visual width and height - * of the drawn text. The lines property contains an array of strings, one for - * each line of text that will be drawn, accounting for line breaks and wrapping. These strings have trailing - * whitespace removed. - * @method getMetrics - * @return {Object} An object with width, height, and lines properties. - **/ - p.getMetrics = function() { - var o = {lines:[]}; - o.lineHeight = this.lineHeight || this.getMeasuredLineHeight(); - o.vOffset = o.lineHeight * Text.V_OFFSETS[this.textBaseline||"top"]; - return this._drawText(null, o, o.lines); - }; - - /** - * Returns a clone of the Text instance. - * @method clone - * @return {Text} a clone of the Text instance. - **/ - p.clone = function() { - return this._cloneProps(new Text(this.text, this.font, this.color)); - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Text (text="+ (this.text.length > 20 ? this.text.substr(0, 17)+"..." : this.text) +")]"; - }; - - -// private methods: - /** - * @method _cloneProps - * @param {Text} o - * @protected - * @return {Text} o - **/ - p._cloneProps = function(o) { - this.DisplayObject__cloneProps(o); - o.textAlign = this.textAlign; - o.textBaseline = this.textBaseline; - o.maxWidth = this.maxWidth; - o.outline = this.outline; - o.lineHeight = this.lineHeight; - o.lineWidth = this.lineWidth; - return o; - }; - - /** - * @method _getWorkingContext - * @param {CanvasRenderingContext2D} ctx - * @return {CanvasRenderingContext2D} - * @protected - **/ - p._prepContext = function(ctx) { - ctx.font = this.font||"10px sans-serif"; - ctx.textAlign = this.textAlign||"left"; - ctx.textBaseline = this.textBaseline||"top"; - return ctx; - }; - - /** - * Draws multiline text. - * @method _drawText - * @param {CanvasRenderingContext2D} ctx - * @param {Object} o - * @param {Array} lines - * @return {Object} - * @protected - **/ - p._drawText = function(ctx, o, lines) { - var paint = !!ctx; - if (!paint) { - ctx = Text._workingContext; - ctx.save(); - this._prepContext(ctx); - } - var lineHeight = this.lineHeight||this.getMeasuredLineHeight(); - - var maxW = 0, count = 0; - var hardLines = String(this.text).split(/(?:\r\n|\r|\n)/); - for (var i=0, l=hardLines.length; i this.lineWidth) { - // text wrapping: - var words = str.split(/(\s)/); - str = words[0]; - w = ctx.measureText(str).width; - - for (var j=1, jl=words.length; j this.lineWidth) { - if (paint) { this._drawTextLine(ctx, str, count*lineHeight); } - if (lines) { lines.push(str); } - if (w > maxW) { maxW = w; } - str = words[j+1]; - w = ctx.measureText(str).width; - count++; - } else { - str += words[j] + words[j+1]; - w += wordW; - } - } - } - - if (paint) { this._drawTextLine(ctx, str, count*lineHeight); } - if (lines) { lines.push(str); } - if (o && w == null) { w = ctx.measureText(str).width; } - if (w > maxW) { maxW = w; } - count++; - } - - if (o) { - o.width = maxW; - o.height = count*lineHeight; - } - if (!paint) { ctx.restore(); } - return o; - }; - - /** - * @method _drawTextLine - * @param {CanvasRenderingContext2D} ctx - * @param {String} text - * @param {Number} y - * @protected - **/ - p._drawTextLine = function(ctx, text, y) { - // Chrome 17 will fail to draw the text if the last param is included but null, so we feed it a large value instead: - if (this.outline) { ctx.strokeText(text, 0, y, this.maxWidth||0xFFFF); } - else { ctx.fillText(text, 0, y, this.maxWidth||0xFFFF); } - }; - - - /** - * @method _getMeasuredWidth - * @param {String} text - * @protected - **/ - p._getMeasuredWidth = function(text) { - var ctx = Text._workingContext; - ctx.save(); - var w = this._prepContext(ctx).measureText(text).width; - ctx.restore(); - return w; - }; - - - createjs.Text = createjs.promote(Text, "DisplayObject"); + createjs.DOMElement = createjs.promote(DOMElement, "DisplayObject"); }()); //############################################################################## -// BitmapText.js +// Filter.js //############################################################################## -this.createjs = this.createjs || {}; - -(function () { - "use strict"; - - -// constructor: - /** - * Displays text using bitmap glyphs defined in a sprite sheet. Multi-line text is supported - * using new line characters, but automatic wrapping is not supported. See the - * {{#crossLink "BitmapText/spriteSheet:property"}}{{/crossLink}} - * property for more information on defining glyphs. - * - * Important: BitmapText extends Container, but is not designed to be used as one. - * As such, methods like addChild and removeChild are disabled. - * @class BitmapText - * @extends DisplayObject - * @param {String} [text=""] The text to display. - * @param {SpriteSheet} [spriteSheet=null] The spritesheet that defines the character glyphs. - * @constructor - **/ - function BitmapText(text, spriteSheet) { - this.Container_constructor(); - - - // public properties: - /** - * The text to display. - * @property text - * @type String - * @default "" - **/ - this.text = text||""; - - /** - * A SpriteSheet instance that defines the glyphs for this bitmap text. Each glyph/character - * should have a single frame animation defined in the sprite sheet named the same as - * corresponding character. For example, the following animation definition: - * - * "A": {frames: [0]} - * - * would indicate that the frame at index 0 of the spritesheet should be drawn for the "A" character. The short form - * is also acceptable: - * - * "A": 0 - * - * Note that if a character in the text is not found in the sprite sheet, it will also - * try to use the alternate case (upper or lower). - * - * See SpriteSheet for more information on defining sprite sheet data. - * @property spriteSheet - * @type SpriteSheet - * @default null - **/ - this.spriteSheet = spriteSheet; - - /** - * The height of each line of text. If 0, then it will use a line height calculated - * by checking for the height of the "1", "T", or "L" character (in that order). If - * those characters are not defined, it will use the height of the first frame of the - * sprite sheet. - * @property lineHeight - * @type Number - * @default 0 - **/ - this.lineHeight = 0; - - /** - * This spacing (in pixels) will be added after each character in the output. - * @property letterSpacing - * @type Number - * @default 0 - **/ - this.letterSpacing = 0; - - /** - * If a space character is not defined in the sprite sheet, then empty pixels equal to - * spaceWidth will be inserted instead. If 0, then it will use a value calculated - * by checking for the width of the "1", "l", "E", or "A" character (in that order). If - * those characters are not defined, it will use the width of the first frame of the - * sprite sheet. - * @property spaceWidth - * @type Number - * @default 0 - **/ - this.spaceWidth = 0; - - - // private properties: - /** - * @property _oldProps - * @type Object - * @protected - **/ - this._oldProps = {text:0,spriteSheet:0,lineHeight:0,letterSpacing:0,spaceWidth:0}; - } - var p = createjs.extend(BitmapText, createjs.Container); - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - -// static properties: - /** - * BitmapText uses Sprite instances to draw text. To reduce the creation and destruction of instances (and thus garbage collection), it maintains - * an internal object pool of sprite instances to reuse. Increasing this value can cause more sprites to be - * retained, slightly increasing memory use, but reducing instantiation. - * @property maxPoolSize - * @type Number - * @static - * @default 100 - **/ - BitmapText.maxPoolSize = 100; - - /** - * Sprite object pool. - * @type {Array} - * @static - * @private - */ - BitmapText._spritePool = []; - - -// public methods: - /** - * Docced in superclass. - **/ - p.draw = function(ctx, ignoreCache) { - if (this.DisplayObject_draw(ctx, ignoreCache)) { return; } - this._updateText(); - this.Container_draw(ctx, ignoreCache); - }; - - /** - * Docced in superclass. - **/ - p.getBounds = function() { - this._updateText(); - return this.Container_getBounds(); - }; - - /** - * Returns true or false indicating whether the display object would be visible if drawn to a canvas. - * This does not account for whether it would be visible within the boundaries of the stage. - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method isVisible - * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas - **/ - p.isVisible = function() { - var hasContent = this.cacheCanvas || (this.spriteSheet && this.spriteSheet.complete && this.text); - return !!(this.visible && this.alpha > 0 && this.scaleX !== 0 && this.scaleY !== 0 && hasContent); - }; - - p.clone = function() { - return this._cloneProps(new BitmapText(this.text, this.spriteSheet)); - }; - - /** - * Disabled in BitmapText. - * @method addChild - **/ - /** - * Disabled in BitmapText. - * @method addChildAt - **/ - /** - * Disabled in BitmapText. - * @method removeChild - **/ - /** - * Disabled in BitmapText. - * @method removeChildAt - **/ - /** - * Disabled in BitmapText. - * @method removeAllChildren - **/ - p.addChild = p.addChildAt = p.removeChild = p.removeChildAt = p.removeAllChildren = function() {}; - - -// private methods: - /** - * @method _cloneProps - * @param {BitmapText} o - * @return {BitmapText} o - * @protected - **/ - p._cloneProps = function(o) { - this.Container__cloneProps(o); - o.lineHeight = this.lineHeight; - o.letterSpacing = this.letterSpacing; - o.spaceWidth = this.spaceWidth; - return o; - }; - - /** - * @method _getFrameIndex - * @param {String} character - * @param {SpriteSheet} spriteSheet - * @return {Number} - * @protected - **/ - p._getFrameIndex = function(character, spriteSheet) { - var c, o = spriteSheet.getAnimation(character); - if (!o) { - (character != (c = character.toUpperCase())) || (character != (c = character.toLowerCase())) || (c=null); - if (c) { o = spriteSheet.getAnimation(c); } - } - return o && o.frames[0]; - }; - - /** - * @method _getFrame - * @param {String} character - * @param {SpriteSheet} spriteSheet - * @return {Object} - * @protected - **/ - p._getFrame = function(character, spriteSheet) { - var index = this._getFrameIndex(character, spriteSheet); - return index == null ? index : spriteSheet.getFrame(index); - }; - - /** - * @method _getLineHeight - * @param {SpriteSheet} ss - * @return {Number} - * @protected - **/ - p._getLineHeight = function(ss) { - var frame = this._getFrame("1",ss) || this._getFrame("T",ss) || this._getFrame("L",ss) || ss.getFrame(0); - return frame ? frame.rect.height : 1; - }; - /** - * @method _getSpaceWidth - * @param {SpriteSheet} ss - * @return {Number} - * @protected - **/ - p._getSpaceWidth = function(ss) { - var frame = this._getFrame("1",ss) || this._getFrame("l",ss) || this._getFrame("e",ss) || this._getFrame("a",ss) || ss.getFrame(0); - return frame ? frame.rect.width : 1; - }; - - /** - * @method _drawText - * @protected - **/ - p._updateText = function() { - var x=0, y=0, o=this._oldProps, change=false, spaceW=this.spaceWidth, lineH=this.lineHeight, ss=this.spriteSheet; - var pool=BitmapText._spritePool, kids=this.children, childIndex=0, numKids=kids.length, sprite; - - for (var n in o) { - if (o[n] != this[n]) { - o[n] = this[n]; - change = true; - } - } - if (!change) { return; } - - var hasSpace = !!this._getFrame(" ", ss); - if (!hasSpace && !spaceW) { spaceW = this._getSpaceWidth(ss); } - if (!lineH) { lineH = this._getLineHeight(ss); } - - for(var i=0, l=this.text.length; i childIndex) { - // faster than removeChild. - pool.push(sprite = kids.pop()); - sprite.parent = null; - numKids--; - } - if (pool.length > BitmapText.maxPoolSize) { pool.length = BitmapText.maxPoolSize; } - }; - - - createjs.BitmapText = createjs.promote(BitmapText, "Container"); +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Base class that all filters should inherit from. Filters need to be applied to objects that have been cached using + * the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method. If an object changes, please cache it again, or use + * {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}}. Note that the filters must be applied before caching. + * + *

      Example

      + * + * myInstance.filters = [ + * new createjs.ColorFilter(0, 0, 0, 1, 255, 0, 0), + * new createjs.BlurFilter(5, 5, 10) + * ]; + * myInstance.cache(0,0, 100, 100); + * + * Note that each filter can implement a {{#crossLink "Filter/getBounds"}}{{/crossLink}} method, which returns the + * margins that need to be applied in order to fully display the filter. For example, the {{#crossLink "BlurFilter"}}{{/crossLink}} + * will cause an object to feather outwards, resulting in a margin around the shape. + * + *

      EaselJS Filters

      + * EaselJS comes with a number of pre-built filters: + *
      • {{#crossLink "AlphaMapFilter"}}{{/crossLink}} : Map a greyscale image to the alpha channel of a display object
      • + *
      • {{#crossLink "AlphaMaskFilter"}}{{/crossLink}}: Map an image's alpha channel to the alpha channel of a display object
      • + *
      • {{#crossLink "BlurFilter"}}{{/crossLink}}: Apply vertical and horizontal blur to a display object
      • + *
      • {{#crossLink "ColorFilter"}}{{/crossLink}}: Color transform a display object
      • + *
      • {{#crossLink "ColorMatrixFilter"}}{{/crossLink}}: Transform an image using a {{#crossLink "ColorMatrix"}}{{/crossLink}}
      • + *
      + * + * @class Filter + * @constructor + **/ + function Filter() {} + var p = Filter.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// public methods: + /** + * Provides padding values for this filter. That is, how much the filter will extend the visual bounds of an object it is applied to. + * @method getBounds + * @param {Rectangle} [rect] If specified, the provided Rectangle instance will be expanded by the padding amounts and returned. + * @return {Rectangle} If a `rect` param was provided, it is returned. If not, either a new rectangle with the padding values, or null if no padding is required for this filter. + **/ + p.getBounds = function(rect) { + return rect; + }; + + /** + * Applies the filter to the specified context. + * @method applyFilter + * @param {CanvasRenderingContext2D} ctx The 2D context to use as the source. + * @param {Number} x The x position to use for the source rect. + * @param {Number} y The y position to use for the source rect. + * @param {Number} width The width to use for the source rect. + * @param {Number} height The height to use for the source rect. + * @param {CanvasRenderingContext2D} [targetCtx] The 2D context to draw the result to. Defaults to the context passed to ctx. + * @param {Number} [targetX] The x position to draw the result to. Defaults to the value passed to x. + * @param {Number} [targetY] The y position to draw the result to. Defaults to the value passed to y. + * @return {Boolean} If the filter was applied successfully. + **/ + p.applyFilter = function(ctx, x, y, width, height, targetCtx, targetX, targetY) { + // this is the default behaviour because most filters access pixel data. It is overridden when not needed. + targetCtx = targetCtx || ctx; + if (targetX == null) { targetX = x; } + if (targetY == null) { targetY = y; } + try { + var imageData = ctx.getImageData(x, y, width, height); + } catch (e) { + return false; + } + if (this._applyFilter(imageData)) { + targetCtx.putImageData(imageData, targetX, targetY); + return true; + } + return false; + }; + + /** + * Returns a string representation of this object. + * @method toString + * @return {String} a string representation of the instance. + **/ + p.toString = function() { + return "[Filter]"; + }; + + /** + * Returns a clone of this Filter instance. + * @method clone + * @return {Filter} A clone of the current Filter instance. + **/ + p.clone = function() { + return new Filter(); + }; + +// private methods: + /** + * @method _applyFilter + * @param {ImageData} imageData Target ImageData instance. + * @return {Boolean} + **/ + p._applyFilter = function(imageData) { return true; }; + + + createjs.Filter = Filter; }()); //############################################################################## -// SpriteSheetUtils.js +// BlurFilter.js //############################################################################## this.createjs = this.createjs||{}; (function() { "use strict"; - - + + // constructor: /** - * The SpriteSheetUtils class is a collection of static methods for working with {{#crossLink "SpriteSheet"}}{{/crossLink}}s. - * A sprite sheet is a series of images (usually animation frames) combined into a single image on a regular grid. For - * example, an animation consisting of 8 100x100 images could be combined into a 400x200 sprite sheet (4 frames across - * by 2 high). The SpriteSheetUtils class uses a static interface and should not be instantiated. - * @class SpriteSheetUtils - * @static + * Applies a box blur to DisplayObjects. Note that this filter is fairly CPU intensive, particularly if the quality is + * set higher than 1. + * + *

      Example

      + * This example creates a red circle, and then applies a 5 pixel blur to it. It uses the {{#crossLink "Filter/getBounds"}}{{/crossLink}} + * method to account for the spread that the blur causes. + * + * var shape = new createjs.Shape().set({x:100,y:100}); + * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); + * + * var blurFilter = new createjs.BlurFilter(5, 5, 1); + * shape.filters = [blurFilter]; + * var bounds = blurFilter.getBounds(); + * + * shape.cache(-50+bounds.x, -50+bounds.y, 100+bounds.width, 100+bounds.height); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. + * @class BlurFilter + * @extends Filter + * @constructor + * @param {Number} [blurX=0] The horizontal blur radius in pixels. + * @param {Number} [blurY=0] The vertical blur radius in pixels. + * @param {Number} [quality=1] The number of blur iterations. **/ - function SpriteSheetUtils() { - throw "SpriteSheetUtils cannot be instantiated"; + function BlurFilter( blurX, blurY, quality) { + if ( isNaN(blurX) || blurX < 0 ) blurX = 0; + if ( isNaN(blurY) || blurY < 0 ) blurY = 0; + if ( isNaN(quality) || quality < 1 ) quality = 1; + + + // public properties: + /** + * Horizontal blur radius in pixels + * @property blurX + * @default 0 + * @type Number + **/ + this.blurX = blurX | 0; + + /** + * Vertical blur radius in pixels + * @property blurY + * @default 0 + * @type Number + **/ + this.blurY = blurY | 0; + + /** + * Number of blur iterations. For example, a value of 1 will produce a rough blur. A value of 2 will produce a + * smoother blur, but take twice as long to run. + * @property quality + * @default 1 + * @type Number + **/ + this.quality = quality | 0; } + var p = createjs.extend(BlurFilter, createjs.Filter); + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. -// private static properties: + +// constants: /** - * @property _workingCanvas - * @static - * @type HTMLCanvasElement | Object + * Array of multiply values for blur calculations. + * @property MUL_TABLE + * @type Array * @protected - */ - /** - * @property _workingContext * @static - * @type CanvasRenderingContext2D - * @protected - */ - var canvas = (createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")); - if (canvas.getContext) { - SpriteSheetUtils._workingCanvas = canvas; - SpriteSheetUtils._workingContext = canvas.getContext("2d"); - canvas.width = canvas.height = 1; - } - + **/ + BlurFilter.MUL_TABLE = [1, 171, 205, 293, 57, 373, 79, 137, 241, 27, 391, 357, 41, 19, 283, 265, 497, 469, 443, 421, 25, 191, 365, 349, 335, 161, 155, 149, 9, 278, 269, 261, 505, 245, 475, 231, 449, 437, 213, 415, 405, 395, 193, 377, 369, 361, 353, 345, 169, 331, 325, 319, 313, 307, 301, 37, 145, 285, 281, 69, 271, 267, 263, 259, 509, 501, 493, 243, 479, 118, 465, 459, 113, 446, 55, 435, 429, 423, 209, 413, 51, 403, 199, 393, 97, 3, 379, 375, 371, 367, 363, 359, 355, 351, 347, 43, 85, 337, 333, 165, 327, 323, 5, 317, 157, 311, 77, 305, 303, 75, 297, 294, 73, 289, 287, 71, 141, 279, 277, 275, 68, 135, 67, 133, 33, 262, 260, 129, 511, 507, 503, 499, 495, 491, 61, 121, 481, 477, 237, 235, 467, 232, 115, 457, 227, 451, 7, 445, 221, 439, 218, 433, 215, 427, 425, 211, 419, 417, 207, 411, 409, 203, 202, 401, 399, 396, 197, 49, 389, 387, 385, 383, 95, 189, 47, 187, 93, 185, 23, 183, 91, 181, 45, 179, 89, 177, 11, 175, 87, 173, 345, 343, 341, 339, 337, 21, 167, 83, 331, 329, 327, 163, 81, 323, 321, 319, 159, 79, 315, 313, 39, 155, 309, 307, 153, 305, 303, 151, 75, 299, 149, 37, 295, 147, 73, 291, 145, 289, 287, 143, 285, 71, 141, 281, 35, 279, 139, 69, 275, 137, 273, 17, 271, 135, 269, 267, 133, 265, 33, 263, 131, 261, 130, 259, 129, 257, 1]; -// public static methods: /** - * This is an experimental method, and may be buggy. Please report issues.

      - * Extends the existing sprite sheet by flipping the original frames horizontally, vertically, or both, - * and adding appropriate animation & frame data. The flipped animations will have a suffix added to their names - * (_h, _v, _hv as appropriate). Make sure the sprite sheet images are fully loaded before using this method. - *

      - * For example:
      - * SpriteSheetUtils.addFlippedFrames(mySpriteSheet, true, true); - * The above would add frames that are flipped horizontally AND frames that are flipped vertically. - *

      - * Note that you can also flip any display object by setting its scaleX or scaleY to a negative value. On some - * browsers (especially those without hardware accelerated canvas) this can result in slightly degraded performance, - * which is why addFlippedFrames is available. - * @method addFlippedFrames + * Array of shift values for blur calculations. + * @property SHG_TABLE + * @type Array + * @protected * @static - * @param {SpriteSheet} spriteSheet - * @param {Boolean} horizontal If true, horizontally flipped frames will be added. - * @param {Boolean} vertical If true, vertically flipped frames will be added. - * @param {Boolean} both If true, frames that are flipped both horizontally and vertically will be added. - * @deprecated Modern browsers perform better when flipping via a transform (ex. scaleX=-1) rendering this obsolete. **/ - SpriteSheetUtils.addFlippedFrames = function(spriteSheet, horizontal, vertical, both) { - if (!horizontal && !vertical && !both) { return; } + BlurFilter.SHG_TABLE = [0, 9, 10, 11, 9, 12, 10, 11, 12, 9, 13, 13, 10, 9, 13, 13, 14, 14, 14, 14, 10, 13, 14, 14, 14, 13, 13, 13, 9, 14, 14, 14, 15, 14, 15, 14, 15, 15, 14, 15, 15, 15, 14, 15, 15, 15, 15, 15, 14, 15, 15, 15, 15, 15, 15, 12, 14, 15, 15, 13, 15, 15, 15, 15, 16, 16, 16, 15, 16, 14, 16, 16, 14, 16, 13, 16, 16, 16, 15, 16, 13, 16, 15, 16, 14, 9, 16, 16, 16, 16, 16, 16, 16, 16, 16, 13, 14, 16, 16, 15, 16, 16, 10, 16, 15, 16, 14, 16, 16, 14, 16, 16, 14, 16, 16, 14, 15, 16, 16, 16, 14, 15, 14, 15, 13, 16, 16, 15, 17, 17, 17, 17, 17, 17, 14, 15, 17, 17, 16, 16, 17, 16, 15, 17, 16, 17, 11, 17, 16, 17, 16, 17, 16, 17, 17, 16, 17, 17, 16, 17, 17, 16, 16, 17, 17, 17, 16, 14, 17, 17, 17, 17, 15, 16, 14, 16, 15, 16, 13, 16, 15, 16, 14, 16, 15, 16, 12, 16, 15, 16, 17, 17, 17, 17, 17, 13, 16, 15, 17, 17, 17, 16, 15, 17, 17, 17, 16, 15, 17, 17, 14, 16, 17, 17, 16, 17, 17, 16, 15, 17, 16, 14, 17, 16, 15, 17, 16, 17, 17, 16, 17, 15, 16, 17, 14, 17, 16, 15, 17, 16, 17, 13, 17, 16, 17, 17, 16, 17, 14, 17, 16, 17, 16, 17, 16, 17, 9]; - var count = 0; - if (horizontal) { SpriteSheetUtils._flip(spriteSheet,++count,true,false); } - if (vertical) { SpriteSheetUtils._flip(spriteSheet,++count,false,true); } - if (both) { SpriteSheetUtils._flip(spriteSheet,++count,true,true); } +// public methods: + /** docced in super class **/ + p.getBounds = function (rect) { + var x = this.blurX|0, y = this.blurY| 0; + if (x <= 0 && y <= 0) { return rect; } + var q = Math.pow(this.quality, 0.2); + return (rect || new createjs.Rectangle()).pad(x*q+1,y*q+1,x*q+1,y*q+1); }; - /** - * Returns a single frame of the specified sprite sheet as a new PNG image. An example of when this may be useful is - * to use a spritesheet frame as the source for a bitmap fill. - * - * WARNING: In almost all cases it is better to display a single frame using a {{#crossLink "Sprite"}}{{/crossLink}} - * with a {{#crossLink "Sprite/gotoAndStop"}}{{/crossLink}} call than it is to slice out a frame using this - * method and display it with a Bitmap instance. You can also crop an image using the {{#crossLink "Bitmap/sourceRect"}}{{/crossLink}} - * property of {{#crossLink "Bitmap"}}{{/crossLink}}. - * - * The extractFrame method may cause cross-domain warnings since it accesses pixels directly on the canvas. - * @method extractFrame - * @static - * @param {SpriteSheet} spriteSheet The SpriteSheet instance to extract a frame from. - * @param {Number|String} frameOrAnimation The frame number or animation name to extract. If an animation - * name is specified, only the first frame of the animation will be extracted. - * @return {HTMLImageElement} a single frame of the specified sprite sheet as a new PNG image. - */ - SpriteSheetUtils.extractFrame = function(spriteSheet, frameOrAnimation) { - if (isNaN(frameOrAnimation)) { - frameOrAnimation = spriteSheet.getAnimation(frameOrAnimation).frames[0]; - } - var data = spriteSheet.getFrame(frameOrAnimation); - if (!data) { return null; } - var r = data.rect; - var canvas = SpriteSheetUtils._workingCanvas; - canvas.width = r.width; - canvas.height = r.height; - SpriteSheetUtils._workingContext.drawImage(data.image, r.x, r.y, r.width, r.height, 0, 0, r.width, r.height); - var img = document.createElement("img"); - img.src = canvas.toDataURL("image/png"); - return img; + /** docced in super class **/ + p.clone = function() { + return new BlurFilter(this.blurX, this.blurY, this.quality); }; - /** - * Merges the rgb channels of one image with the alpha channel of another. This can be used to combine a compressed - * JPEG image containing color data with a PNG32 monochromatic image containing alpha data. With certain types of - * images (those with detail that lend itself to JPEG compression) this can provide significant file size savings - * versus a single RGBA PNG32. This method is very fast (generally on the order of 1-2 ms to run). - * @method mergeAlpha - * @static - * @param {HTMLImageElement} rbgImage The image (or canvas) containing the RGB channels to use. - * @param {HTMLImageElement} alphaImage The image (or canvas) containing the alpha channel to use. - * @param {HTMLCanvasElement} canvas Optional. If specified, this canvas will be used and returned. If not, a new canvas will be created. - * @return {HTMLCanvasElement} A canvas with the combined image data. This can be used as a source for Bitmap or SpriteSheet. - * @deprecated Tools such as ImageAlpha generally provide better results. This will be moved to sandbox in the future. - */ - SpriteSheetUtils.mergeAlpha = function(rgbImage, alphaImage, canvas) { - if (!canvas) { canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); } - canvas.width = Math.max(alphaImage.width, rgbImage.width); - canvas.height = Math.max(alphaImage.height, rgbImage.height); - var ctx = canvas.getContext("2d"); - ctx.save(); - ctx.drawImage(rgbImage,0,0); - ctx.globalCompositeOperation = "destination-in"; - ctx.drawImage(alphaImage,0,0); - ctx.restore(); - return canvas; + /** docced in super class **/ + p.toString = function() { + return "[BlurFilter]"; }; -// private static methods: - SpriteSheetUtils._flip = function(spriteSheet, count, h, v) { - var imgs = spriteSheet._images; - var canvas = SpriteSheetUtils._workingCanvas; - var ctx = SpriteSheetUtils._workingContext; - var il = imgs.length/count; - for (var i=0;i> 1; + if (isNaN(radiusX) || radiusX < 0) return false; + var radiusY = this.blurY >> 1; + if (isNaN(radiusY) || radiusY < 0) return false; + if (radiusX == 0 && radiusY == 0) return false; + + var iterations = this.quality; + if (isNaN(iterations) || iterations < 1) iterations = 1; + iterations |= 0; + if (iterations > 3) iterations = 3; + if (iterations < 1) iterations = 1; + + var px = imageData.data; + var x=0, y=0, i=0, p=0, yp=0, yi=0, yw=0, r=0, g=0, b=0, a=0, pr=0, pg=0, pb=0, pa=0; + + var divx = (radiusX + radiusX + 1) | 0; + var divy = (radiusY + radiusY + 1) | 0; + var w = imageData.width | 0; + var h = imageData.height | 0; + + var w1 = (w - 1) | 0; + var h1 = (h - 1) | 0; + var rxp1 = (radiusX + 1) | 0; + var ryp1 = (radiusY + 1) | 0; + + var ssx = {r:0,b:0,g:0,a:0}; + var sx = ssx; + for ( i = 1; i < divx; i++ ) + { + sx = sx.n = {r:0,b:0,g:0,a:0}; + } + sx.n = ssx; + + var ssy = {r:0,b:0,g:0,a:0}; + var sy = ssy; + for ( i = 1; i < divy; i++ ) + { + sy = sy.n = {r:0,b:0,g:0,a:0}; } + sy.n = ssy; + + var si = null; + + + var mtx = BlurFilter.MUL_TABLE[radiusX] | 0; + var stx = BlurFilter.SHG_TABLE[radiusX] | 0; + var mty = BlurFilter.MUL_TABLE[radiusY] | 0; + var sty = BlurFilter.SHG_TABLE[radiusY] | 0; + + while (iterations-- > 0) { + + yw = yi = 0; + var ms = mtx; + var ss = stx; + for (y = h; --y > -1;) { + r = rxp1 * (pr = px[(yi) | 0]); + g = rxp1 * (pg = px[(yi + 1) | 0]); + b = rxp1 * (pb = px[(yi + 2) | 0]); + a = rxp1 * (pa = px[(yi + 3) | 0]); + + sx = ssx; + + for( i = rxp1; --i > -1; ) + { + sx.r = pr; + sx.g = pg; + sx.b = pb; + sx.a = pa; + sx = sx.n; + } + + for( i = 1; i < rxp1; i++ ) + { + p = (yi + ((w1 < i ? w1 : i) << 2)) | 0; + r += ( sx.r = px[p]); + g += ( sx.g = px[p+1]); + b += ( sx.b = px[p+2]); + a += ( sx.a = px[p+3]); + + sx = sx.n; + } + + si = ssx; + for ( x = 0; x < w; x++ ) + { + px[yi++] = (r * ms) >>> ss; + px[yi++] = (g * ms) >>> ss; + px[yi++] = (b * ms) >>> ss; + px[yi++] = (a * ms) >>> ss; + + p = ((yw + ((p = x + radiusX + 1) < w1 ? p : w1)) << 2); + + r -= si.r - ( si.r = px[p]); + g -= si.g - ( si.g = px[p+1]); + b -= si.b - ( si.b = px[p+2]); + a -= si.a - ( si.a = px[p+3]); + + si = si.n; + + } + yw += w; + } + + ms = mty; + ss = sty; + for (x = 0; x < w; x++) { + yi = (x << 2) | 0; + + r = (ryp1 * (pr = px[yi])) | 0; + g = (ryp1 * (pg = px[(yi + 1) | 0])) | 0; + b = (ryp1 * (pb = px[(yi + 2) | 0])) | 0; + a = (ryp1 * (pa = px[(yi + 3) | 0])) | 0; + + sy = ssy; + for( i = 0; i < ryp1; i++ ) + { + sy.r = pr; + sy.g = pg; + sy.b = pb; + sy.a = pa; + sy = sy.n; + } + + yp = w; + + for( i = 1; i <= radiusY; i++ ) + { + yi = ( yp + x ) << 2; + + r += ( sy.r = px[yi]); + g += ( sy.g = px[yi+1]); + b += ( sy.b = px[yi+2]); + a += ( sy.a = px[yi+3]); + + sy = sy.n; + + if( i < h1 ) + { + yp += w; + } + } + + yi = x; + si = ssy; + if ( iterations > 0 ) + { + for ( y = 0; y < h; y++ ) + { + p = yi << 2; + px[p+3] = pa =(a * ms) >>> ss; + if ( pa > 0 ) + { + px[p] = ((r * ms) >>> ss ); + px[p+1] = ((g * ms) >>> ss ); + px[p+2] = ((b * ms) >>> ss ); + } else { + px[p] = px[p+1] = px[p+2] = 0 + } + + p = ( x + (( ( p = y + ryp1) < h1 ? p : h1 ) * w )) << 2; + + r -= si.r - ( si.r = px[p]); + g -= si.g - ( si.g = px[p+1]); + b -= si.b - ( si.b = px[p+2]); + a -= si.a - ( si.a = px[p+3]); + + si = si.n; - var frames = spriteSheet._frames; - var fl = frames.length/count; - for (i=0;i>> ss; + if ( pa > 0 ) + { + pa = 255 / pa; + px[p] = ((r * ms) >>> ss ) * pa; + px[p+1] = ((g * ms) >>> ss ) * pa; + px[p+2] = ((b * ms) >>> ss ) * pa; + } else { + px[p] = px[p+1] = px[p+2] = 0 + } - var frame = {image:img,rect:rect,regX:src.regX,regY:src.regY}; - if (h) { - rect.x = img.width-rect.x-rect.width; // update rect - frame.regX = rect.width-src.regX; // update registration point - } - if (v) { - rect.y = img.height-rect.y-rect.height; // update rect - frame.regY = rect.height-src.regY; // update registration point - } - frames.push(frame); - } + p = ( x + (( ( p = y + ryp1) < h1 ? p : h1 ) * w )) << 2; - var sfx = "_"+(h?"h":"")+(v?"v":""); - var names = spriteSheet._animations; - var data = spriteSheet._data; - var al = names.length/count; - for (i=0;imaxWidth or maxHeight. - * @class SpriteSheetBuilder - * @extends EventDispatcher - * @constructor - **/ - function SpriteSheetBuilder() { - this.EventDispatcher_constructor(); - - // public properties: - /** - * The maximum width for the images (not individual frames) in the generated sprite sheet. It is recommended to use - * a power of 2 for this value (ex. 1024, 2048, 4096). If the frames cannot all fit within the max dimensions, then - * additional images will be created as needed. - * @property maxWidth - * @type Number - * @default 2048 - */ - this.maxWidth = 2048; - - /** - * The maximum height for the images (not individual frames) in the generated sprite sheet. It is recommended to use - * a power of 2 for this value (ex. 1024, 2048, 4096). If the frames cannot all fit within the max dimensions, then - * additional images will be created as needed. - * @property maxHeight - * @type Number - * @default 2048 - **/ - this.maxHeight = 2048; - - /** - * The sprite sheet that was generated. This will be null before a build is completed successfully. - * @property spriteSheet - * @type SpriteSheet - **/ - this.spriteSheet = null; - - /** - * The scale to apply when drawing all frames to the sprite sheet. This is multiplied against any scale specified - * in the addFrame call. This can be used, for example, to generate a sprite sheet at run time that is tailored to - * the a specific device resolution (ex. tablet vs mobile). - * @property scale - * @type Number - * @default 1 - **/ - this.scale = 1; - - /** - * The padding to use between frames. This is helpful to preserve antialiasing on drawn vector content. - * @property padding - * @type Number - * @default 1 - **/ - this.padding = 1; - - /** - * A number from 0.01 to 0.99 that indicates what percentage of time the builder can use. This can be - * thought of as the number of seconds per second the builder will use. For example, with a timeSlice value of 0.3, - * the builder will run 20 times per second, using approximately 15ms per build (30% of available time, or 0.3s per second). - * Defaults to 0.3. - * @property timeSlice - * @type Number - * @default 0.3 - **/ - this.timeSlice = 0.3; - - /** - * A value between 0 and 1 that indicates the progress of a build, or -1 if a build has not - * been initiated. - * @property progress - * @type Number - * @default -1 - * @readonly - **/ - this.progress = -1; - - - // private properties: - /** - * @property _frames - * @protected - * @type Array - **/ - this._frames = []; - - /** - * @property _animations - * @protected - * @type Array - **/ - this._animations = {}; - - /** - * @property _data - * @protected - * @type Array - **/ - this._data = null; - - /** - * @property _nextFrameIndex - * @protected - * @type Number - **/ - this._nextFrameIndex = 0; - - /** - * @property _index - * @protected - * @type Number - **/ - this._index = 0; - - /** - * @property _timerID - * @protected - * @type Number - **/ - this._timerID = null; - - /** - * @property _scale - * @protected - * @type Number - **/ - this._scale = 1; - } - var p = createjs.extend(SpriteSheetBuilder, createjs.EventDispatcher); - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// constants: - SpriteSheetBuilder.ERR_DIMENSIONS = "frame dimensions exceed max spritesheet dimensions"; - SpriteSheetBuilder.ERR_RUNNING = "a build is already running"; - -// events: - /** - * Dispatched when a build completes. - * @event complete - * @param {Object} target The object that dispatched the event. - * @param {String} type The event type. - * @since 0.6.0 - */ - - /** - * Dispatched when an asynchronous build has progress. - * @event progress - * @param {Object} target The object that dispatched the event. - * @param {String} type The event type. - * @param {Number} progress The current progress value (0-1). - * @since 0.6.0 - */ - - -// public methods: - /** - * Adds a frame to the {{#crossLink "SpriteSheet"}}{{/crossLink}}. Note that the frame will not be drawn until you - * call {{#crossLink "SpriteSheetBuilder/build"}}{{/crossLink}} method. The optional setup params allow you to have - * a function run immediately before the draw occurs. For example, this allows you to add a single source multiple - * times, but manipulate it or its children to change it to generate different frames. - * - * Note that the source's transformations (x, y, scale, rotate, alpha) will be ignored, except for regX/Y. To apply - * transforms to a source object and have them captured in the sprite sheet, simply place it into a {{#crossLink "Container"}}{{/crossLink}} - * and pass in the Container as the source. - * @method addFrame - * @param {DisplayObject} source The source {{#crossLink "DisplayObject"}}{{/crossLink}} to draw as the frame. - * @param {Rectangle} [sourceRect] A {{#crossLink "Rectangle"}}{{/crossLink}} defining the portion of the - * source to draw to the frame. If not specified, it will look for a getBounds method, bounds property, - * or nominalBounds property on the source to use. If one is not found, the frame will be skipped. - * @param {Number} [scale=1] Optional. The scale to draw this frame at. Default is 1. - * @param {Function} [setupFunction] A function to call immediately before drawing this frame. It will be called with two parameters: the source, and setupData. - * @param {Object} [setupData] Arbitrary setup data to pass to setupFunction as the second parameter. - * @return {Number} The index of the frame that was just added, or null if a sourceRect could not be determined. - **/ - p.addFrame = function(source, sourceRect, scale, setupFunction, setupData) { - if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } - var rect = sourceRect||source.bounds||source.nominalBounds; - if (!rect&&source.getBounds) { rect = source.getBounds(); } - if (!rect) { return null; } - scale = scale||1; - return this._frames.push({source:source, sourceRect:rect, scale:scale, funct:setupFunction, data:setupData, index:this._frames.length, height:rect.height*scale})-1; - }; - - /** - * Adds an animation that will be included in the created sprite sheet. - * @method addAnimation - * @param {String} name The name for the animation. - * @param {Array} frames An array of frame indexes that comprise the animation. Ex. [3,6,5] would describe an animation - * that played frame indexes 3, 6, and 5 in that order. - * @param {String} [next] Specifies the name of the animation to continue to after this animation ends. You can - * also pass false to have the animation stop when it ends. By default it will loop to the start of the same animation. - * @param {Number} [frequency] Specifies a frame advance frequency for this animation. For example, a value - * of 2 would cause the animation to advance every second tick. - **/ - p.addAnimation = function(name, frames, next, frequency) { - if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } - this._animations[name] = {frames:frames, next:next, frequency:frequency}; - }; - - /** - * This will take a MovieClip instance, and add its frames and labels to this builder. Labels will be added as an animation - * running from the label index to the next label. For example, if there is a label named "foo" at frame 0 and a label - * named "bar" at frame 10, in a MovieClip with 15 frames, it will add an animation named "foo" that runs from frame - * index 0 to 9, and an animation named "bar" that runs from frame index 10 to 14. - * - * Note that this will iterate through the full MovieClip with actionsEnabled set to false, ending on the last frame. - * @method addMovieClip - * @param {MovieClip} source The source MovieClip instance to add to the sprite sheet. - * @param {Rectangle} [sourceRect] A {{#crossLink "Rectangle"}}{{/crossLink}} defining the portion of the source to - * draw to the frame. If not specified, it will look for a getBounds method, frameBounds - * Array, bounds property, or nominalBounds property on the source to use. If one is not - * found, the MovieClip will be skipped. - * @param {Number} [scale=1] The scale to draw the movie clip at. - * @param {Function} [setupFunction] A function to call immediately before drawing each frame. It will be called with three parameters: the source, setupData, and the frame index. - * @param {Object} [setupData] Arbitrary setup data to pass to setupFunction as the second parameter. - * @param {Function} [labelFunction] This method will be called for each movieclip label that is added with four parameters: the label name, the source movieclip instance, the starting frame index (in the movieclip timeline) and the end index. It must return a new name for the label/animation, or false to exclude the label. - **/ - p.addMovieClip = function(source, sourceRect, scale, setupFunction, setupData, labelFunction) { - if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } - var rects = source.frameBounds; - var rect = sourceRect||source.bounds||source.nominalBounds; - if (!rect&&source.getBounds) { rect = source.getBounds(); } - if (!rect && !rects) { return; } - - var i, l, baseFrameIndex = this._frames.length; - var duration = source.timeline.duration; - for (i=0; itimeSlice. When it is complete it will - * call the specified callback. - * @method buildAsync - * @param {Number} [timeSlice] Sets the timeSlice property on this instance. - **/ - p.buildAsync = function(timeSlice) { - if (this._data) { throw SpriteSheetBuilder.ERR_RUNNING; } - this.timeSlice = timeSlice; - this._startBuild(); - var _this = this; - this._timerID = setTimeout(function() { _this._run(); }, 50-Math.max(0.01, Math.min(0.99, this.timeSlice||0.3))*50); - }; - - /** - * Stops the current asynchronous build. - * @method stopAsync - **/ - p.stopAsync = function() { - clearTimeout(this._timerID); - this._data = null; - }; - - /** - * SpriteSheetBuilder instances cannot be cloned. - * @method clone - **/ - p.clone = function() { - throw("SpriteSheetBuilder cannot be cloned."); - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[SpriteSheetBuilder]"; - }; - - -// private methods: - /** - * @method _startBuild - * @protected - **/ - p._startBuild = function() { - var pad = this.padding||0; - this.progress = 0; - this.spriteSheet = null; - this._index = 0; - this._scale = this.scale; - var dataFrames = []; - this._data = { - images: [], - frames: dataFrames, - animations: this._animations // TODO: should we "clone" _animations in case someone adds more animations after a build? - }; - - var frames = this._frames.slice(); - frames.sort(function(a,b) { return (a.height<=b.height) ? -1 : 1; }); - - if (frames[frames.length-1].height+pad*2 > this.maxHeight) { throw SpriteSheetBuilder.ERR_DIMENSIONS; } - var y=0, x=0; - var img = 0; - while (frames.length) { - var o = this._fillRow(frames, y, img, dataFrames, pad); - if (o.w > x) { x = o.w; } - y += o.h; - if (!o.h || !frames.length) { - var canvas = createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"); - canvas.width = this._getSize(x,this.maxWidth); - canvas.height = this._getSize(y,this.maxHeight); - this._data.images[img] = canvas; - if (!o.h) { - x=y=0; - img++; - } - } - } - }; - - /** - * @method _setupMovieClipFrame - * @protected - * @return {Number} The width & height of the row. - **/ - p._setupMovieClipFrame = function(source, data) { - var ae = source.actionsEnabled; - source.actionsEnabled = false; - source.gotoAndStop(data.i); - source.actionsEnabled = ae; - data.f&&data.f(source, data.d, data.i); - }; - - /** - * @method _getSize - * @protected - * @return {Number} The width & height of the row. - **/ - p._getSize = function(size,max) { - var pow = 4; - while (Math.pow(2,++pow) < size){} - return Math.min(max,Math.pow(2,pow)); - }; - - /** - * @method _fillRow - * @param {Array} frames - * @param {Number} y - * @param {HTMLImageElement} img - * @param {Object} dataFrames - * @param {Number} pad - * @protected - * @return {Number} The width & height of the row. - **/ - p._fillRow = function(frames, y, img, dataFrames, pad) { - var w = this.maxWidth; - var maxH = this.maxHeight; - y += pad; - var h = maxH-y; - var x = pad; - var height = 0; - for (var i=frames.length-1; i>=0; i--) { - var frame = frames[i]; - var sc = this._scale*frame.scale; - var rect = frame.sourceRect; - var source = frame.source; - var rx = Math.floor(sc*rect.x-pad); - var ry = Math.floor(sc*rect.y-pad); - var rh = Math.ceil(sc*rect.height+pad*2); - var rw = Math.ceil(sc*rect.width+pad*2); - if (rw > w) { throw SpriteSheetBuilder.ERR_DIMENSIONS; } - if (rh > h || x+rw > w) { continue; } - frame.img = img; - frame.rect = new createjs.Rectangle(x,y,rw,rh); - height = height || rh; - frames.splice(i,1); - dataFrames[frame.index] = [x,y,rw,rh,img,Math.round(-rx+sc*source.regX-pad),Math.round(-ry+sc*source.regY-pad)]; - x += rw; - } - return {w:x, h:height}; - }; - - /** - * @method _endBuild - * @protected - **/ - p._endBuild = function() { - this.spriteSheet = new createjs.SpriteSheet(this._data); - this._data = null; - this.progress = 1; - this.dispatchEvent("complete"); - }; - - /** - * @method _run - * @protected - **/ - p._run = function() { - var ts = Math.max(0.01, Math.min(0.99, this.timeSlice||0.3))*50; - var t = (new Date()).getTime()+ts; - var complete = false; - while (t > (new Date()).getTime()) { - if (!this._drawNext()) { complete = true; break; } - } - if (complete) { - this._endBuild(); - } else { - var _this = this; - this._timerID = setTimeout(function() { _this._run(); }, 50-ts); - } - var p = this.progress = this._index/this._frames.length; - if (this.hasEventListener("progress")) { - var evt = new createjs.Event("progress"); - evt.progress = p; - this.dispatchEvent(evt); - } - }; - - /** - * @method _drawNext - * @protected - * @return Boolean Returns false if this is the last draw. - **/ - p._drawNext = function() { - var frame = this._frames[this._index]; - var sc = frame.scale*this._scale; - var rect = frame.rect; - var sourceRect = frame.sourceRect; - var canvas = this._data.images[frame.img]; - var ctx = canvas.getContext("2d"); - frame.funct&&frame.funct(frame.source, frame.data); - ctx.save(); - ctx.beginPath(); - ctx.rect(rect.x, rect.y, rect.width, rect.height); - ctx.clip(); - ctx.translate(Math.ceil(rect.x-sourceRect.x*sc), Math.ceil(rect.y-sourceRect.y*sc)); - ctx.scale(sc,sc); - frame.source.draw(ctx); // display object will draw itself. - ctx.restore(); - return (++this._index) < this._frames.length; - }; - - - createjs.SpriteSheetBuilder = createjs.promote(SpriteSheetBuilder, "EventDispatcher"); -}()); - -//############################################################################## -// DOMElement.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * This class is still experimental, and more advanced use is likely to be buggy. Please report bugs. - * - * A DOMElement allows you to associate a HTMLElement with the display list. It will be transformed - * within the DOM as though it is child of the {{#crossLink "Container"}}{{/crossLink}} it is added to. However, it is - * not rendered to canvas, and as such will retain whatever z-index it has relative to the canvas (ie. it will be - * drawn in front of or behind the canvas). - * - * The position of a DOMElement is relative to their parent node in the DOM. It is recommended that - * the DOM Object be added to a div that also contains the canvas so that they share the same position - * on the page. - * - * DOMElement is useful for positioning HTML elements over top of canvas content, and for elements - * that you want to display outside the bounds of the canvas. For example, a tooltip with rich HTML - * content. - * - *

      Mouse Interaction

      - * - * DOMElement instances are not full EaselJS display objects, and do not participate in EaselJS mouse - * events or support methods like hitTest. To get mouse events from a DOMElement, you must instead add handlers to - * the htmlElement (note, this does not support EventDispatcher) - * - * var domElement = new createjs.DOMElement(htmlElement); - * domElement.htmlElement.onclick = function() { - * console.log("clicked"); - * } - * - * @class DOMElement - * @extends DisplayObject - * @constructor - * @param {HTMLElement} htmlElement A reference or id for the DOM element to manage. - */ - function DOMElement(htmlElement) { - this.DisplayObject_constructor(); - - if (typeof(htmlElement)=="string") { htmlElement = document.getElementById(htmlElement); } - this.mouseEnabled = false; - - var style = htmlElement.style; - style.position = "absolute"; - style.transformOrigin = style.WebkitTransformOrigin = style.msTransformOrigin = style.MozTransformOrigin = style.OTransformOrigin = "0% 0%"; - - - // public properties: - /** - * The DOM object to manage. - * @property htmlElement - * @type HTMLElement - */ - this.htmlElement = htmlElement; - - - // private properties: - /** - * @property _oldMtx - * @type Matrix2D - * @protected - */ - this._oldProps = null; - } - var p = createjs.extend(DOMElement, createjs.DisplayObject); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// public methods: - /** - * Returns true or false indicating whether the display object would be visible if drawn to a canvas. - * This does not account for whether it would be visible within the boundaries of the stage. - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method isVisible - * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas - */ - p.isVisible = function() { - return this.htmlElement != null; - }; - - /** - * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform. - * Returns true if the draw was handled (useful for overriding functionality). - * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. - * @method draw - * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. - * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. - * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back - * into itself). - * @return {Boolean} - */ - p.draw = function(ctx, ignoreCache) { - // this relies on the _tick method because draw isn't called if the parent is not visible. - // the actual update happens in _handleDrawEnd - return true; - }; - - /** - * Not applicable to DOMElement. - * @method cache - */ - p.cache = function() {}; - - /** - * Not applicable to DOMElement. - * @method uncache - */ - p.uncache = function() {}; - - /** - * Not applicable to DOMElement. - * @method updateCache - */ - p.updateCache = function() {}; - - /** - * Not applicable to DOMElement. - * @method hitTest - */ - p.hitTest = function() {}; - - /** - * Not applicable to DOMElement. - * @method localToGlobal - */ - p.localToGlobal = function() {}; - - /** - * Not applicable to DOMElement. - * @method globalToLocal - */ - p.globalToLocal = function() {}; - - /** - * Not applicable to DOMElement. - * @method localToLocal - */ - p.localToLocal = function() {}; - - /** - * DOMElement cannot be cloned. Throws an error. - * @method clone - */ - p.clone = function() { - throw("DOMElement cannot be cloned.") - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - */ - p.toString = function() { - return "[DOMElement (name="+ this.name +")]"; - }; - - /** - * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances - * are not full EaselJS display objects and do not participate in EaselJS mouse events. - * @event click - */ - - /** - * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances - * are not full EaselJS display objects and do not participate in EaselJS mouse events. - * @event dblClick - */ - - /** - * Interaction events should be added to `htmlElement`, and not the DOMElement instance, since DOMElement instances - * are not full EaselJS display objects and do not participate in EaselJS mouse events. - * @event mousedown - */ - - /** - * The HTMLElement can listen for the mouseover event, not the DOMElement instance. - * Since DOMElement instances are not full EaselJS display objects and do not participate in EaselJS mouse events. - * @event mouseover - */ - - /** - * Not applicable to DOMElement. - * @event tick - */ - - -// private methods: - /** - * @method _tick - * @param {Object} evtObj An event object that will be dispatched to all tick listeners. This object is reused between dispatchers to reduce construction & GC costs. - * function. - * @protected - */ - p._tick = function(evtObj) { - var stage = this.getStage(); - stage&&stage.on("drawend", this._handleDrawEnd, this, true); - this.DisplayObject__tick(evtObj); - }; - - /** - * @method _handleDrawEnd - * @param {Event} evt - * @protected - */ - p._handleDrawEnd = function(evt) { - var o = this.htmlElement; - if (!o) { return; } - var style = o.style; - - var props = this.getConcatenatedDisplayProps(this._props), mtx = props.matrix; - - var visibility = props.visible ? "visible" : "hidden"; - if (visibility != style.visibility) { style.visibility = visibility; } - if (!props.visible) { return; } - - var oldProps = this._oldProps, oldMtx = oldProps&&oldProps.matrix; - var n = 10000; // precision - - if (!oldMtx || !oldMtx.equals(mtx)) { - var str = "matrix(" + (mtx.a*n|0)/n +","+ (mtx.b*n|0)/n +","+ (mtx.c*n|0)/n +","+ (mtx.d*n|0)/n +","+ (mtx.tx+0.5|0); - style.transform = style.WebkitTransform = style.OTransform = style.msTransform = str +","+ (mtx.ty+0.5|0) +")"; - style.MozTransform = str +"px,"+ (mtx.ty+0.5|0) +"px)"; - if (!oldProps) { oldProps = this._oldProps = new createjs.DisplayProps(true, NaN); } - oldProps.matrix.copy(mtx); - } - - if (oldProps.alpha != props.alpha) { - style.opacity = ""+(props.alpha*n|0)/n; - oldProps.alpha = props.alpha; - } - }; - - - createjs.DOMElement = createjs.promote(DOMElement, "DisplayObject"); -}()); - -//############################################################################## -// Filter.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Base class that all filters should inherit from. Filters need to be applied to objects that have been cached using - * the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method. If an object changes, please cache it again, or use - * {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}}. Note that the filters must be applied before caching. - * - *

      Example

      - * - * myInstance.filters = [ - * new createjs.ColorFilter(0, 0, 0, 1, 255, 0, 0), - * new createjs.BlurFilter(5, 5, 10) - * ]; - * myInstance.cache(0,0, 100, 100); - * - * Note that each filter can implement a {{#crossLink "Filter/getBounds"}}{{/crossLink}} method, which returns the - * margins that need to be applied in order to fully display the filter. For example, the {{#crossLink "BlurFilter"}}{{/crossLink}} - * will cause an object to feather outwards, resulting in a margin around the shape. - * - *

      EaselJS Filters

      - * EaselJS comes with a number of pre-built filters. Note that individual filters are not compiled into the minified - * version of EaselJS. To use them, you must include them manually in the HTML. - *
      • {{#crossLink "AlphaMapFilter"}}{{/crossLink}} : Map a greyscale image to the alpha channel of a display object
      • - *
      • {{#crossLink "AlphaMaskFilter"}}{{/crossLink}}: Map an image's alpha channel to the alpha channel of a display object
      • - *
      • {{#crossLink "BlurFilter"}}{{/crossLink}}: Apply vertical and horizontal blur to a display object
      • - *
      • {{#crossLink "ColorFilter"}}{{/crossLink}}: Color transform a display object
      • - *
      • {{#crossLink "ColorMatrixFilter"}}{{/crossLink}}: Transform an image using a {{#crossLink "ColorMatrix"}}{{/crossLink}}
      • - *
      - * - * @class Filter - * @constructor - **/ - function Filter() {} - var p = Filter.prototype; - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// public methods: - /** - * Provides padding values for this filter. That is, how much the filter will extend the visual bounds of an object it is applied to. - * @method getBounds - * @param {Rectangle} [rect] If specified, the provided Rectangle instance will be expanded by the padding amounts and returned. - * @return {Rectangle} If a `rect` param was provided, it is returned. If not, either a new rectangle with the padding values, or null if no padding is required for this filter. - **/ - p.getBounds = function(rect) { - return rect; - }; - - /** - * Applies the filter to the specified context. - * @method applyFilter - * @param {CanvasRenderingContext2D} ctx The 2D context to use as the source. - * @param {Number} x The x position to use for the source rect. - * @param {Number} y The y position to use for the source rect. - * @param {Number} width The width to use for the source rect. - * @param {Number} height The height to use for the source rect. - * @param {CanvasRenderingContext2D} [targetCtx] The 2D context to draw the result to. Defaults to the context passed to ctx. - * @param {Number} [targetX] The x position to draw the result to. Defaults to the value passed to x. - * @param {Number} [targetY] The y position to draw the result to. Defaults to the value passed to y. - * @return {Boolean} If the filter was applied successfully. - **/ - p.applyFilter = function(ctx, x, y, width, height, targetCtx, targetX, targetY) { - // this is the default behaviour because most filters access pixel data. It is overridden when not needed. - targetCtx = targetCtx || ctx; - if (targetX == null) { targetX = x; } - if (targetY == null) { targetY = y; } - try { - var imageData = ctx.getImageData(x, y, width, height); - } catch (e) { - return false; - } - if (this._applyFilter(imageData)) { - targetCtx.putImageData(imageData, targetX, targetY); - return true; - } - return false; - }; - - /** - * Returns a string representation of this object. - * @method toString - * @return {String} a string representation of the instance. - **/ - p.toString = function() { - return "[Filter]"; - }; - - /** - * Returns a clone of this Filter instance. - * @method clone - * @return {Filter} A clone of the current Filter instance. - **/ - p.clone = function() { - return new Filter(); - }; - -// private methods: - /** - * @method _applyFilter - * @param {ImageData} imageData Target ImageData instance. - * @return {Boolean} - **/ - p._applyFilter = function(imageData) { return true; }; - - - createjs.Filter = Filter; -}()); - -//############################################################################## -// BlurFilter.js -//############################################################################## - -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Applies a box blur to DisplayObjects. Note that this filter is fairly CPU intensive, particularly if the quality is - * set higher than 1. - * - *

      Example

      - * This example creates a red circle, and then applies a 5 pixel blur to it. It uses the {{#crossLink "Filter/getBounds"}}{{/crossLink}} - * method to account for the spread that the blur causes. - * - * var shape = new createjs.Shape().set({x:100,y:100}); - * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); - * - * var blurFilter = new createjs.BlurFilter(5, 5, 1); - * shape.filters = [blurFilter]; - * var bounds = blurFilter.getBounds(); - * - * shape.cache(-50+bounds.x, -50+bounds.y, 100+bounds.width, 100+bounds.height); - * - * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. - * @class BlurFilter - * @extends Filter - * @constructor - * @param {Number} [blurX=0] The horizontal blur radius in pixels. - * @param {Number} [blurY=0] The vertical blur radius in pixels. - * @param {Number} [quality=1] The number of blur iterations. - **/ - function BlurFilter( blurX, blurY, quality) { - if ( isNaN(blurX) || blurX < 0 ) blurX = 0; - if ( isNaN(blurY) || blurY < 0 ) blurY = 0; - if ( isNaN(quality) || quality < 1 ) quality = 1; - - - // public properties: - /** - * Horizontal blur radius in pixels - * @property blurX - * @default 0 - * @type Number - **/ - this.blurX = blurX | 0; - - /** - * Vertical blur radius in pixels - * @property blurY - * @default 0 - * @type Number - **/ - this.blurY = blurY | 0; - - /** - * Number of blur iterations. For example, a value of 1 will produce a rough blur. A value of 2 will produce a - * smoother blur, but take twice as long to run. - * @property quality - * @default 1 - * @type Number - **/ - this.quality = quality | 0; - } - var p = createjs.extend(BlurFilter, createjs.Filter); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// constants: - /** - * Array of multiply values for blur calculations. - * @property MUL_TABLE - * @type Array - * @protected - * @static - **/ - BlurFilter.MUL_TABLE = [1, 171, 205, 293, 57, 373, 79, 137, 241, 27, 391, 357, 41, 19, 283, 265, 497, 469, 443, 421, 25, 191, 365, 349, 335, 161, 155, 149, 9, 278, 269, 261, 505, 245, 475, 231, 449, 437, 213, 415, 405, 395, 193, 377, 369, 361, 353, 345, 169, 331, 325, 319, 313, 307, 301, 37, 145, 285, 281, 69, 271, 267, 263, 259, 509, 501, 493, 243, 479, 118, 465, 459, 113, 446, 55, 435, 429, 423, 209, 413, 51, 403, 199, 393, 97, 3, 379, 375, 371, 367, 363, 359, 355, 351, 347, 43, 85, 337, 333, 165, 327, 323, 5, 317, 157, 311, 77, 305, 303, 75, 297, 294, 73, 289, 287, 71, 141, 279, 277, 275, 68, 135, 67, 133, 33, 262, 260, 129, 511, 507, 503, 499, 495, 491, 61, 121, 481, 477, 237, 235, 467, 232, 115, 457, 227, 451, 7, 445, 221, 439, 218, 433, 215, 427, 425, 211, 419, 417, 207, 411, 409, 203, 202, 401, 399, 396, 197, 49, 389, 387, 385, 383, 95, 189, 47, 187, 93, 185, 23, 183, 91, 181, 45, 179, 89, 177, 11, 175, 87, 173, 345, 343, 341, 339, 337, 21, 167, 83, 331, 329, 327, 163, 81, 323, 321, 319, 159, 79, 315, 313, 39, 155, 309, 307, 153, 305, 303, 151, 75, 299, 149, 37, 295, 147, 73, 291, 145, 289, 287, 143, 285, 71, 141, 281, 35, 279, 139, 69, 275, 137, 273, 17, 271, 135, 269, 267, 133, 265, 33, 263, 131, 261, 130, 259, 129, 257, 1]; - - /** - * Array of shift values for blur calculations. - * @property SHG_TABLE - * @type Array - * @protected - * @static - **/ - BlurFilter.SHG_TABLE = [0, 9, 10, 11, 9, 12, 10, 11, 12, 9, 13, 13, 10, 9, 13, 13, 14, 14, 14, 14, 10, 13, 14, 14, 14, 13, 13, 13, 9, 14, 14, 14, 15, 14, 15, 14, 15, 15, 14, 15, 15, 15, 14, 15, 15, 15, 15, 15, 14, 15, 15, 15, 15, 15, 15, 12, 14, 15, 15, 13, 15, 15, 15, 15, 16, 16, 16, 15, 16, 14, 16, 16, 14, 16, 13, 16, 16, 16, 15, 16, 13, 16, 15, 16, 14, 9, 16, 16, 16, 16, 16, 16, 16, 16, 16, 13, 14, 16, 16, 15, 16, 16, 10, 16, 15, 16, 14, 16, 16, 14, 16, 16, 14, 16, 16, 14, 15, 16, 16, 16, 14, 15, 14, 15, 13, 16, 16, 15, 17, 17, 17, 17, 17, 17, 14, 15, 17, 17, 16, 16, 17, 16, 15, 17, 16, 17, 11, 17, 16, 17, 16, 17, 16, 17, 17, 16, 17, 17, 16, 17, 17, 16, 16, 17, 17, 17, 16, 14, 17, 17, 17, 17, 15, 16, 14, 16, 15, 16, 13, 16, 15, 16, 14, 16, 15, 16, 12, 16, 15, 16, 17, 17, 17, 17, 17, 13, 16, 15, 17, 17, 17, 16, 15, 17, 17, 17, 16, 15, 17, 17, 14, 16, 17, 17, 16, 17, 17, 16, 15, 17, 16, 14, 17, 16, 15, 17, 16, 17, 17, 16, 17, 15, 16, 17, 14, 17, 16, 15, 17, 16, 17, 13, 17, 16, 17, 17, 16, 17, 14, 17, 16, 17, 16, 17, 16, 17, 9]; - -// public methods: - /** docced in super class **/ - p.getBounds = function (rect) { - var x = this.blurX|0, y = this.blurY| 0; - if (x <= 0 && y <= 0) { return rect; } - var q = Math.pow(this.quality, 0.2); - return (rect || new createjs.Rectangle()).pad(x*q+1,y*q+1,x*q+1,y*q+1); - }; - - /** docced in super class **/ - p.clone = function() { - return new BlurFilter(this.blurX, this.blurY, this.quality); - }; - - /** docced in super class **/ - p.toString = function() { - return "[BlurFilter]"; - }; - - -// private methods: - - /** docced in super class **/ - p._applyFilter = function (imageData) { - - var radiusX = this.blurX >> 1; - if (isNaN(radiusX) || radiusX < 0) return false; - var radiusY = this.blurY >> 1; - if (isNaN(radiusY) || radiusY < 0) return false; - if (radiusX == 0 && radiusY == 0) return false; - - var iterations = this.quality; - if (isNaN(iterations) || iterations < 1) iterations = 1; - iterations |= 0; - if (iterations > 3) iterations = 3; - if (iterations < 1) iterations = 1; - - var px = imageData.data; - var x=0, y=0, i=0, p=0, yp=0, yi=0, yw=0, r=0, g=0, b=0, a=0, pr=0, pg=0, pb=0, pa=0; - - var divx = (radiusX + radiusX + 1) | 0; - var divy = (radiusY + radiusY + 1) | 0; - var w = imageData.width | 0; - var h = imageData.height | 0; - - var w1 = (w - 1) | 0; - var h1 = (h - 1) | 0; - var rxp1 = (radiusX + 1) | 0; - var ryp1 = (radiusY + 1) | 0; - - var ssx = {r:0,b:0,g:0,a:0}; - var sx = ssx; - for ( i = 1; i < divx; i++ ) - { - sx = sx.n = {r:0,b:0,g:0,a:0}; - } - sx.n = ssx; - - var ssy = {r:0,b:0,g:0,a:0}; - var sy = ssy; - for ( i = 1; i < divy; i++ ) - { - sy = sy.n = {r:0,b:0,g:0,a:0}; - } - sy.n = ssy; - - var si = null; - - - var mtx = BlurFilter.MUL_TABLE[radiusX] | 0; - var stx = BlurFilter.SHG_TABLE[radiusX] | 0; - var mty = BlurFilter.MUL_TABLE[radiusY] | 0; - var sty = BlurFilter.SHG_TABLE[radiusY] | 0; - - while (iterations-- > 0) { - - yw = yi = 0; - var ms = mtx; - var ss = stx; - for (y = h; --y > -1;) { - r = rxp1 * (pr = px[(yi) | 0]); - g = rxp1 * (pg = px[(yi + 1) | 0]); - b = rxp1 * (pb = px[(yi + 2) | 0]); - a = rxp1 * (pa = px[(yi + 3) | 0]); - - sx = ssx; - - for( i = rxp1; --i > -1; ) - { - sx.r = pr; - sx.g = pg; - sx.b = pb; - sx.a = pa; - sx = sx.n; - } - - for( i = 1; i < rxp1; i++ ) - { - p = (yi + ((w1 < i ? w1 : i) << 2)) | 0; - r += ( sx.r = px[p]); - g += ( sx.g = px[p+1]); - b += ( sx.b = px[p+2]); - a += ( sx.a = px[p+3]); - - sx = sx.n; - } - - si = ssx; - for ( x = 0; x < w; x++ ) - { - px[yi++] = (r * ms) >>> ss; - px[yi++] = (g * ms) >>> ss; - px[yi++] = (b * ms) >>> ss; - px[yi++] = (a * ms) >>> ss; - - p = ((yw + ((p = x + radiusX + 1) < w1 ? p : w1)) << 2); - - r -= si.r - ( si.r = px[p]); - g -= si.g - ( si.g = px[p+1]); - b -= si.b - ( si.b = px[p+2]); - a -= si.a - ( si.a = px[p+3]); - - si = si.n; - - } - yw += w; - } - - ms = mty; - ss = sty; - for (x = 0; x < w; x++) { - yi = (x << 2) | 0; - - r = (ryp1 * (pr = px[yi])) | 0; - g = (ryp1 * (pg = px[(yi + 1) | 0])) | 0; - b = (ryp1 * (pb = px[(yi + 2) | 0])) | 0; - a = (ryp1 * (pa = px[(yi + 3) | 0])) | 0; - - sy = ssy; - for( i = 0; i < ryp1; i++ ) - { - sy.r = pr; - sy.g = pg; - sy.b = pb; - sy.a = pa; - sy = sy.n; - } - - yp = w; - - for( i = 1; i <= radiusY; i++ ) - { - yi = ( yp + x ) << 2; - - r += ( sy.r = px[yi]); - g += ( sy.g = px[yi+1]); - b += ( sy.b = px[yi+2]); - a += ( sy.a = px[yi+3]); - - sy = sy.n; - - if( i < h1 ) - { - yp += w; - } - } - - yi = x; - si = ssy; - if ( iterations > 0 ) - { - for ( y = 0; y < h; y++ ) - { - p = yi << 2; - px[p+3] = pa =(a * ms) >>> ss; - if ( pa > 0 ) - { - px[p] = ((r * ms) >>> ss ); - px[p+1] = ((g * ms) >>> ss ); - px[p+2] = ((b * ms) >>> ss ); - } else { - px[p] = px[p+1] = px[p+2] = 0 - } - - p = ( x + (( ( p = y + ryp1) < h1 ? p : h1 ) * w )) << 2; - - r -= si.r - ( si.r = px[p]); - g -= si.g - ( si.g = px[p+1]); - b -= si.b - ( si.b = px[p+2]); - a -= si.a - ( si.a = px[p+3]); - - si = si.n; - - yi += w; - } - } else { - for ( y = 0; y < h; y++ ) - { - p = yi << 2; - px[p+3] = pa =(a * ms) >>> ss; - if ( pa > 0 ) - { - pa = 255 / pa; - px[p] = ((r * ms) >>> ss ) * pa; - px[p+1] = ((g * ms) >>> ss ) * pa; - px[p+2] = ((b * ms) >>> ss ) * pa; - } else { - px[p] = px[p+1] = px[p+2] = 0 - } - - p = ( x + (( ( p = y + ryp1) < h1 ? p : h1 ) * w )) << 2; - - r -= si.r - ( si.r = px[p]); - g -= si.g - ( si.g = px[p+1]); - b -= si.b - ( si.b = px[p+2]); - a -= si.a - ( si.a = px[p+3]); - - si = si.n; - - yi += w; - } - } - } - - } - return true; - }; - - createjs.BlurFilter = createjs.promote(BlurFilter, "Filter"); + createjs.BlurFilter = createjs.promote(BlurFilter, "Filter"); }()); //############################################################################## // AlphaMapFilter.js //############################################################################## -this.createjs = this.createjs || {}; - -(function () { - "use strict"; - - -// constructor: - /** - * Applies a greyscale alpha map image (or canvas) to the target, such that the alpha channel of the result will - * be copied from the red channel of the map, and the RGB channels will be copied from the target. - * - * Generally, it is recommended that you use {{#crossLink "AlphaMaskFilter"}}{{/crossLink}}, because it has much - * better performance. - * - *

      Example

      - * This example draws a red->blue box, caches it, and then uses the cache canvas as an alpha map on a 100x100 image. - * - * var box = new createjs.Shape(); - * box.graphics.beginLinearGradientFill(["#ff0000", "#0000ff"], [0, 1], 0, 0, 0, 100) - * box.graphics.drawRect(0, 0, 100, 100); - * box.cache(0, 0, 100, 100); - * - * var bmp = new createjs.Bitmap("path/to/image.jpg"); - * bmp.filters = [ - * new createjs.AlphaMapFilter(box.cacheCanvas) - * ]; - * bmp.cache(0, 0, 100, 100); - * stage.addChild(bmp); - * - * See {{#crossLink "Filter"}}{{/crossLink}} for more information on applying filters. - * @class AlphaMapFilter - * @extends Filter - * @constructor - * @param {HTMLImageElement|HTMLCanvasElement} alphaMap The greyscale image (or canvas) to use as the alpha value for the - * result. This should be exactly the same dimensions as the target. - **/ - function AlphaMapFilter(alphaMap) { - - - // public properties: - /** - * The greyscale image (or canvas) to use as the alpha value for the result. This should be exactly the same - * dimensions as the target. - * @property alphaMap - * @type HTMLImageElement|HTMLCanvasElement - **/ - this.alphaMap = alphaMap; - - - // private properties: - /** - * @property _alphaMap - * @protected - * @type HTMLImageElement|HTMLCanvasElement - **/ - this._alphaMap = null; - - /** - * @property _mapData - * @protected - * @type Uint8ClampedArray - **/ - this._mapData = null; - } - var p = createjs.extend(AlphaMapFilter, createjs.Filter); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// public methods: - /** docced in super class **/ - p.clone = function () { - var o = new AlphaMapFilter(this.alphaMap); - o._alphaMap = this._alphaMap; - o._mapData = this._mapData; - return o; - }; - - /** docced in super class **/ - p.toString = function () { - return "[AlphaMapFilter]"; - }; - - -// private methods: - /** docced in super class **/ - p._applyFilter = function (imageData) { - if (!this.alphaMap) { return true; } - if (!this._prepAlphaMap()) { return false; } - - // TODO: update to support scenarios where the target has different dimensions. - var data = imageData.data; - var map = this._mapData; - for(var i=0, l=data.length; iExample + * This example draws a red->blue box, caches it, and then uses the cache canvas as an alpha map on a 100x100 image. + * + * var box = new createjs.Shape(); + * box.graphics.beginLinearGradientFill(["#ff0000", "#0000ff"], [0, 1], 0, 0, 0, 100) + * box.graphics.drawRect(0, 0, 100, 100); + * box.cache(0, 0, 100, 100); + * + * var bmp = new createjs.Bitmap("path/to/image.jpg"); + * bmp.filters = [ + * new createjs.AlphaMapFilter(box.cacheCanvas) + * ]; + * bmp.cache(0, 0, 100, 100); + * stage.addChild(bmp); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for more information on applying filters. + * @class AlphaMapFilter + * @extends Filter + * @constructor + * @param {HTMLImageElement|HTMLCanvasElement} alphaMap The greyscale image (or canvas) to use as the alpha value for the + * result. This should be exactly the same dimensions as the target. + **/ + function AlphaMapFilter(alphaMap) { + + + // public properties: + /** + * The greyscale image (or canvas) to use as the alpha value for the result. This should be exactly the same + * dimensions as the target. + * @property alphaMap + * @type HTMLImageElement|HTMLCanvasElement + **/ + this.alphaMap = alphaMap; + + + // private properties: + /** + * @property _alphaMap + * @protected + * @type HTMLImageElement|HTMLCanvasElement + **/ + this._alphaMap = null; + + /** + * @property _mapData + * @protected + * @type Uint8ClampedArray + **/ + this._mapData = null; + } + var p = createjs.extend(AlphaMapFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** docced in super class **/ + p.clone = function () { + var o = new AlphaMapFilter(this.alphaMap); + o._alphaMap = this._alphaMap; + o._mapData = this._mapData; + return o; + }; + + /** docced in super class **/ + p.toString = function () { + return "[AlphaMapFilter]"; + }; + + +// private methods: + /** docced in super class **/ + p._applyFilter = function (imageData) { + if (!this.alphaMap) { return true; } + if (!this._prepAlphaMap()) { return false; } + + // TODO: update to support scenarios where the target has different dimensions. + var data = imageData.data; + var map = this._mapData; + for(var i=0, l=data.length; iIMPORTANT NOTE: This filter currently does not support the targetCtx, or targetX/Y parameters correctly. - * - *

      Example

      - * This example draws a gradient box, then caches it and uses the "cacheCanvas" as the alpha mask on a 100x100 image. - * - * var box = new createjs.Shape(); - * box.graphics.beginLinearGradientFill(["#000000", "rgba(0, 0, 0, 0)"], [0, 1], 0, 0, 100, 100) - * box.graphics.drawRect(0, 0, 100, 100); - * box.cache(0, 0, 100, 100); - * - * var bmp = new createjs.Bitmap("path/to/image.jpg"); - * bmp.filters = [ - * new createjs.AlphaMaskFilter(box.cacheCanvas) - * ]; - * bmp.cache(0, 0, 100, 100); - * - * See {{#crossLink "Filter"}}{{/crossLink}} for more information on applying filters. - * @class AlphaMaskFilter - * @extends Filter - * @constructor - * @param {HTMLImageElement|HTMLCanvasElement} mask - **/ - function AlphaMaskFilter(mask) { - - - // public properties: - /** - * The image (or canvas) to use as the mask. - * @property mask - * @type HTMLImageElement|HTMLCanvasElement - **/ - this.mask = mask; - } - var p = createjs.extend(AlphaMaskFilter, createjs.Filter); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// public methods: - /** - * Applies the filter to the specified context. - * - * IMPORTANT NOTE: This filter currently does not support the targetCtx, or targetX/Y parameters - * correctly. - * @method applyFilter - * @param {CanvasRenderingContext2D} ctx The 2D context to use as the source. - * @param {Number} x The x position to use for the source rect. - * @param {Number} y The y position to use for the source rect. - * @param {Number} width The width to use for the source rect. - * @param {Number} height The height to use for the source rect. - * @param {CanvasRenderingContext2D} [targetCtx] NOT SUPPORTED IN THIS FILTER. The 2D context to draw the result to. Defaults to the context passed to ctx. - * @param {Number} [targetX] NOT SUPPORTED IN THIS FILTER. The x position to draw the result to. Defaults to the value passed to x. - * @param {Number} [targetY] NOT SUPPORTED IN THIS FILTER. The y position to draw the result to. Defaults to the value passed to y. - * @return {Boolean} If the filter was applied successfully. - **/ - p.applyFilter = function (ctx, x, y, width, height, targetCtx, targetX, targetY) { - if (!this.mask) { return true; } - targetCtx = targetCtx || ctx; - if (targetX == null) { targetX = x; } - if (targetY == null) { targetY = y; } - - targetCtx.save(); - if (ctx != targetCtx) { - // TODO: support targetCtx and targetX/Y - // clearRect, then draw the ctx in? - return false; - } - - targetCtx.globalCompositeOperation = "destination-in"; - targetCtx.drawImage(this.mask, targetX, targetY); - targetCtx.restore(); - return true; - }; - - /** docced in super class **/ - p.clone = function () { - return new AlphaMaskFilter(this.mask); - }; - - /** docced in super class **/ - p.toString = function () { - return "[AlphaMaskFilter]"; - }; - - - createjs.AlphaMaskFilter = createjs.promote(AlphaMaskFilter, "Filter"); +this.createjs = this.createjs || {}; + +(function () { + "use strict"; + + +// constructor: + /** + * Applies the alpha from the mask image (or canvas) to the target, such that the alpha channel of the result will + * be derived from the mask, and the RGB channels will be copied from the target. This can be used, for example, to + * apply an alpha mask to a display object. This can also be used to combine a JPG compressed RGB image with a PNG32 + * alpha mask, which can result in a much smaller file size than a single PNG32 containing ARGB. + * + * IMPORTANT NOTE: This filter currently does not support the targetCtx, or targetX/Y parameters correctly. + * + *

      Example

      + * This example draws a gradient box, then caches it and uses the "cacheCanvas" as the alpha mask on a 100x100 image. + * + * var box = new createjs.Shape(); + * box.graphics.beginLinearGradientFill(["#000000", "rgba(0, 0, 0, 0)"], [0, 1], 0, 0, 100, 100) + * box.graphics.drawRect(0, 0, 100, 100); + * box.cache(0, 0, 100, 100); + * + * var bmp = new createjs.Bitmap("path/to/image.jpg"); + * bmp.filters = [ + * new createjs.AlphaMaskFilter(box.cacheCanvas) + * ]; + * bmp.cache(0, 0, 100, 100); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for more information on applying filters. + * @class AlphaMaskFilter + * @extends Filter + * @constructor + * @param {HTMLImageElement|HTMLCanvasElement} mask + **/ + function AlphaMaskFilter(mask) { + + + // public properties: + /** + * The image (or canvas) to use as the mask. + * @property mask + * @type HTMLImageElement|HTMLCanvasElement + **/ + this.mask = mask; + } + var p = createjs.extend(AlphaMaskFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** + * Applies the filter to the specified context. + * + * IMPORTANT NOTE: This filter currently does not support the targetCtx, or targetX/Y parameters + * correctly. + * @method applyFilter + * @param {CanvasRenderingContext2D} ctx The 2D context to use as the source. + * @param {Number} x The x position to use for the source rect. + * @param {Number} y The y position to use for the source rect. + * @param {Number} width The width to use for the source rect. + * @param {Number} height The height to use for the source rect. + * @param {CanvasRenderingContext2D} [targetCtx] NOT SUPPORTED IN THIS FILTER. The 2D context to draw the result to. Defaults to the context passed to ctx. + * @param {Number} [targetX] NOT SUPPORTED IN THIS FILTER. The x position to draw the result to. Defaults to the value passed to x. + * @param {Number} [targetY] NOT SUPPORTED IN THIS FILTER. The y position to draw the result to. Defaults to the value passed to y. + * @return {Boolean} If the filter was applied successfully. + **/ + p.applyFilter = function (ctx, x, y, width, height, targetCtx, targetX, targetY) { + if (!this.mask) { return true; } + targetCtx = targetCtx || ctx; + if (targetX == null) { targetX = x; } + if (targetY == null) { targetY = y; } + + targetCtx.save(); + if (ctx != targetCtx) { + // TODO: support targetCtx and targetX/Y + // clearRect, then draw the ctx in? + return false; + } + + targetCtx.globalCompositeOperation = "destination-in"; + targetCtx.drawImage(this.mask, targetX, targetY); + targetCtx.restore(); + return true; + }; + + /** docced in super class **/ + p.clone = function () { + return new AlphaMaskFilter(this.mask); + }; + + /** docced in super class **/ + p.toString = function () { + return "[AlphaMaskFilter]"; + }; + + + createjs.AlphaMaskFilter = createjs.promote(AlphaMaskFilter, "Filter"); }()); //############################################################################## // ColorFilter.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Applies a color transform to DisplayObjects. - * - *

      Example

      - * This example draws a red circle, and then transforms it to Blue. This is accomplished by multiplying all the channels - * to 0 (except alpha, which is set to 1), and then adding 255 to the blue channel. - * - * var shape = new createjs.Shape().set({x:100,y:100}); - * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); - * - * shape.filters = [ - * new createjs.ColorFilter(0,0,0,1, 0,0,255,0) - * ]; - * shape.cache(-50, -50, 100, 100); - * - * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. - * @class ColorFilter - * @param {Number} [redMultiplier=1] The amount to multiply against the red channel. This is a range between 0 and 1. - * @param {Number} [greenMultiplier=1] The amount to multiply against the green channel. This is a range between 0 and 1. - * @param {Number} [blueMultiplier=1] The amount to multiply against the blue channel. This is a range between 0 and 1. - * @param {Number} [alphaMultiplier=1] The amount to multiply against the alpha channel. This is a range between 0 and 1. - * @param {Number} [redOffset=0] The amount to add to the red channel after it has been multiplied. This is a range - * between -255 and 255. - * @param {Number} [greenOffset=0] The amount to add to the green channel after it has been multiplied. This is a range - * between -255 and 255. - * @param {Number} [blueOffset=0] The amount to add to the blue channel after it has been multiplied. This is a range - * between -255 and 255. - * @param {Number} [alphaOffset=0] The amount to add to the alpha channel after it has been multiplied. This is a range - * between -255 and 255. - * @constructor - * @extends Filter - **/ - function ColorFilter(redMultiplier, greenMultiplier, blueMultiplier, alphaMultiplier, redOffset, greenOffset, blueOffset, alphaOffset) { - - - // public properties: - /** - * Red channel multiplier. - * @property redMultiplier - * @type Number - **/ - this.redMultiplier = redMultiplier != null ? redMultiplier : 1; - - /** - * Green channel multiplier. - * @property greenMultiplier - * @type Number - **/ - this.greenMultiplier = greenMultiplier != null ? greenMultiplier : 1; - - /** - * Blue channel multiplier. - * @property blueMultiplier - * @type Number - **/ - this.blueMultiplier = blueMultiplier != null ? blueMultiplier : 1; - - /** - * Alpha channel multiplier. - * @property alphaMultiplier - * @type Number - **/ - this.alphaMultiplier = alphaMultiplier != null ? alphaMultiplier : 1; - - /** - * Red channel offset (added to value). - * @property redOffset - * @type Number - **/ - this.redOffset = redOffset || 0; - - /** - * Green channel offset (added to value). - * @property greenOffset - * @type Number - **/ - this.greenOffset = greenOffset || 0; - - /** - * Blue channel offset (added to value). - * @property blueOffset - * @type Number - **/ - this.blueOffset = blueOffset || 0; - - /** - * Alpha channel offset (added to value). - * @property alphaOffset - * @type Number - **/ - this.alphaOffset = alphaOffset || 0; - } - var p = createjs.extend(ColorFilter, createjs.Filter); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// public methods: - /** docced in super class **/ - p.toString = function() { - return "[ColorFilter]"; - }; - - /** docced in super class **/ - p.clone = function() { - return new ColorFilter(this.redMultiplier, this.greenMultiplier, this.blueMultiplier, this.alphaMultiplier, this.redOffset, this.greenOffset, this.blueOffset, this.alphaOffset); - }; - - -// private methods: - /** docced in super class **/ - p._applyFilter = function(imageData) { - var data = imageData.data; - var l = data.length; - for (var i=0; iExample + * This example draws a red circle, and then transforms it to Blue. This is accomplished by multiplying all the channels + * to 0 (except alpha, which is set to 1), and then adding 255 to the blue channel. + * + * var shape = new createjs.Shape().set({x:100,y:100}); + * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); + * + * shape.filters = [ + * new createjs.ColorFilter(0,0,0,1, 0,0,255,0) + * ]; + * shape.cache(-50, -50, 100, 100); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. + * @class ColorFilter + * @param {Number} [redMultiplier=1] The amount to multiply against the red channel. This is a range between 0 and 1. + * @param {Number} [greenMultiplier=1] The amount to multiply against the green channel. This is a range between 0 and 1. + * @param {Number} [blueMultiplier=1] The amount to multiply against the blue channel. This is a range between 0 and 1. + * @param {Number} [alphaMultiplier=1] The amount to multiply against the alpha channel. This is a range between 0 and 1. + * @param {Number} [redOffset=0] The amount to add to the red channel after it has been multiplied. This is a range + * between -255 and 255. + * @param {Number} [greenOffset=0] The amount to add to the green channel after it has been multiplied. This is a range + * between -255 and 255. + * @param {Number} [blueOffset=0] The amount to add to the blue channel after it has been multiplied. This is a range + * between -255 and 255. + * @param {Number} [alphaOffset=0] The amount to add to the alpha channel after it has been multiplied. This is a range + * between -255 and 255. + * @constructor + * @extends Filter + **/ + function ColorFilter(redMultiplier, greenMultiplier, blueMultiplier, alphaMultiplier, redOffset, greenOffset, blueOffset, alphaOffset) { + + + // public properties: + /** + * Red channel multiplier. + * @property redMultiplier + * @type Number + **/ + this.redMultiplier = redMultiplier != null ? redMultiplier : 1; + + /** + * Green channel multiplier. + * @property greenMultiplier + * @type Number + **/ + this.greenMultiplier = greenMultiplier != null ? greenMultiplier : 1; + + /** + * Blue channel multiplier. + * @property blueMultiplier + * @type Number + **/ + this.blueMultiplier = blueMultiplier != null ? blueMultiplier : 1; + + /** + * Alpha channel multiplier. + * @property alphaMultiplier + * @type Number + **/ + this.alphaMultiplier = alphaMultiplier != null ? alphaMultiplier : 1; + + /** + * Red channel offset (added to value). + * @property redOffset + * @type Number + **/ + this.redOffset = redOffset || 0; + + /** + * Green channel offset (added to value). + * @property greenOffset + * @type Number + **/ + this.greenOffset = greenOffset || 0; + + /** + * Blue channel offset (added to value). + * @property blueOffset + * @type Number + **/ + this.blueOffset = blueOffset || 0; + + /** + * Alpha channel offset (added to value). + * @property alphaOffset + * @type Number + **/ + this.alphaOffset = alphaOffset || 0; + } + var p = createjs.extend(ColorFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** docced in super class **/ + p.toString = function() { + return "[ColorFilter]"; + }; + + /** docced in super class **/ + p.clone = function() { + return new ColorFilter(this.redMultiplier, this.greenMultiplier, this.blueMultiplier, this.alphaMultiplier, this.redOffset, this.greenOffset, this.blueOffset, this.alphaOffset); + }; + + +// private methods: + /** docced in super class **/ + p._applyFilter = function(imageData) { + var data = imageData.data; + var l = data.length; + for (var i=0; iExample - * - * myColorMatrix.adjustHue(20).adjustBrightness(50); - * - * See {{#crossLink "Filter"}}{{/crossLink}} for an example of how to apply filters, or {{#crossLink "ColorMatrixFilter"}}{{/crossLink}} - * for an example of how to use ColorMatrix to change a DisplayObject's color. - * @class ColorMatrix - * @param {Number} brightness - * @param {Number} contrast - * @param {Number} saturation - * @param {Number} hue - * @constructor - **/ - function ColorMatrix(brightness, contrast, saturation, hue) { - this.setColor(brightness, contrast, saturation, hue); - } - var p = ColorMatrix.prototype; - - /** - * REMOVED. Removed in favor of using `MySuperClass_constructor`. - * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} - * for details. - * - * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. - * - * @method initialize - * @protected - * @deprecated - */ - // p.initialize = function() {}; // searchable for devs wondering where it is. - - -// constants: - /** - * Array of delta values for contrast calculations. - * @property DELTA_INDEX - * @type Array - * @protected - * @static - **/ - ColorMatrix.DELTA_INDEX = [ - 0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11, - 0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24, - 0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42, - 0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68, - 0.71, 0.74, 0.77, 0.80, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98, - 1.0, 1.06, 1.12, 1.18, 1.24, 1.30, 1.36, 1.42, 1.48, 1.54, - 1.60, 1.66, 1.72, 1.78, 1.84, 1.90, 1.96, 2.0, 2.12, 2.25, - 2.37, 2.50, 2.62, 2.75, 2.87, 3.0, 3.2, 3.4, 3.6, 3.8, - 4.0, 4.3, 4.7, 4.9, 5.0, 5.5, 6.0, 6.5, 6.8, 7.0, - 7.3, 7.5, 7.8, 8.0, 8.4, 8.7, 9.0, 9.4, 9.6, 9.8, - 10.0 - ]; - - /** - * Identity matrix values. - * @property IDENTITY_MATRIX - * @type Array - * @protected - * @static - **/ - ColorMatrix.IDENTITY_MATRIX = [ - 1,0,0,0,0, - 0,1,0,0,0, - 0,0,1,0,0, - 0,0,0,1,0, - 0,0,0,0,1 - ]; - - /** - * The constant length of a color matrix. - * @property LENGTH - * @type Number - * @protected - * @static - **/ - ColorMatrix.LENGTH = ColorMatrix.IDENTITY_MATRIX.length; - - -// public methods: - /** - * Resets the instance with the specified values. - * @method setColor - * @param {Number} brightness - * @param {Number} contrast - * @param {Number} saturation - * @param {Number} hue - * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) - * @chainable - */ - p.setColor = function(brightness,contrast,saturation,hue) { - return this.reset().adjustColor(brightness,contrast,saturation,hue); - }; - - /** - * Resets the matrix to identity values. - * @method reset - * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) - * @chainable - */ - p.reset = function() { - return this.copy(ColorMatrix.IDENTITY_MATRIX); - }; - - /** - * Shortcut method to adjust brightness, contrast, saturation and hue. - * Equivalent to calling adjustHue(hue), adjustContrast(contrast), - * adjustBrightness(brightness), adjustSaturation(saturation), in that order. - * @method adjustColor - * @param {Number} brightness - * @param {Number} contrast - * @param {Number} saturation - * @param {Number} hue - * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.adjustColor = function(brightness,contrast,saturation,hue) { - this.adjustHue(hue); - this.adjustContrast(contrast); - this.adjustBrightness(brightness); - return this.adjustSaturation(saturation); - }; - - /** - * Adjusts the brightness of pixel color by adding the specified value to the red, green and blue channels. - * Positive values will make the image brighter, negative values will make it darker. - * @method adjustBrightness - * @param {Number} value A value between -255 & 255 that will be added to the RGB channels. - * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.adjustBrightness = function(value) { - if (value == 0 || isNaN(value)) { return this; } - value = this._cleanValue(value,255); - this._multiplyMatrix([ - 1,0,0,0,value, - 0,1,0,0,value, - 0,0,1,0,value, - 0,0,0,1,0, - 0,0,0,0,1 - ]); - return this; - }; - - /** - * Adjusts the contrast of pixel color. - * Positive values will increase contrast, negative values will decrease contrast. - * @method adjustContrast - * @param {Number} value A value between -100 & 100. - * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.adjustContrast = function(value) { - if (value == 0 || isNaN(value)) { return this; } - value = this._cleanValue(value,100); - var x; - if (value<0) { - x = 127+value/100*127; - } else { - x = value%1; - if (x == 0) { - x = ColorMatrix.DELTA_INDEX[value]; - } else { - x = ColorMatrix.DELTA_INDEX[(value<<0)]*(1-x)+ColorMatrix.DELTA_INDEX[(value<<0)+1]*x; // use linear interpolation for more granularity. - } - x = x*127+127; - } - this._multiplyMatrix([ - x/127,0,0,0,0.5*(127-x), - 0,x/127,0,0,0.5*(127-x), - 0,0,x/127,0,0.5*(127-x), - 0,0,0,1,0, - 0,0,0,0,1 - ]); - return this; - }; - - /** - * Adjusts the color saturation of the pixel. - * Positive values will increase saturation, negative values will decrease saturation (trend towards greyscale). - * @method adjustSaturation - * @param {Number} value A value between -100 & 100. - * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.adjustSaturation = function(value) { - if (value == 0 || isNaN(value)) { return this; } - value = this._cleanValue(value,100); - var x = 1+((value > 0) ? 3*value/100 : value/100); - var lumR = 0.3086; - var lumG = 0.6094; - var lumB = 0.0820; - this._multiplyMatrix([ - lumR*(1-x)+x,lumG*(1-x),lumB*(1-x),0,0, - lumR*(1-x),lumG*(1-x)+x,lumB*(1-x),0,0, - lumR*(1-x),lumG*(1-x),lumB*(1-x)+x,0,0, - 0,0,0,1,0, - 0,0,0,0,1 - ]); - return this; - }; - - - /** - * Adjusts the hue of the pixel color. - * @method adjustHue - * @param {Number} value A value between -180 & 180. - * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.adjustHue = function(value) { - if (value == 0 || isNaN(value)) { return this; } - value = this._cleanValue(value,180)/180*Math.PI; - var cosVal = Math.cos(value); - var sinVal = Math.sin(value); - var lumR = 0.213; - var lumG = 0.715; - var lumB = 0.072; - this._multiplyMatrix([ - lumR+cosVal*(1-lumR)+sinVal*(-lumR),lumG+cosVal*(-lumG)+sinVal*(-lumG),lumB+cosVal*(-lumB)+sinVal*(1-lumB),0,0, - lumR+cosVal*(-lumR)+sinVal*(0.143),lumG+cosVal*(1-lumG)+sinVal*(0.140),lumB+cosVal*(-lumB)+sinVal*(-0.283),0,0, - lumR+cosVal*(-lumR)+sinVal*(-(1-lumR)),lumG+cosVal*(-lumG)+sinVal*(lumG),lumB+cosVal*(1-lumB)+sinVal*(lumB),0,0, - 0,0,0,1,0, - 0,0,0,0,1 - ]); - return this; - }; - - /** - * Concatenates (multiplies) the specified matrix with this one. - * @method concat - * @param {Array} matrix An array or ColorMatrix instance. - * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) - * @chainable - **/ - p.concat = function(matrix) { - matrix = this._fixMatrix(matrix); - if (matrix.length != ColorMatrix.LENGTH) { return this; } - this._multiplyMatrix(matrix); - return this; - }; - - /** - * Returns a clone of this ColorMatrix. - * @method clone - * @return {ColorMatrix} A clone of this ColorMatrix. - **/ - p.clone = function() { - return (new ColorMatrix()).copy(this); - }; - - /** - * Return a length 25 (5x5) array instance containing this matrix's values. - * @method toArray - * @return {Array} An array holding this matrix's values. - **/ - p.toArray = function() { - var arr = []; - for (var i= 0, l=ColorMatrix.LENGTH; i ColorMatrix.LENGTH) { - matrix = matrix.slice(0,ColorMatrix.LENGTH); - } - return matrix; - }; - - - createjs.ColorMatrix = ColorMatrix; +this.createjs = this.createjs||{}; + +(function() { + "use strict"; + + +// constructor: + /** + * Provides helper functions for assembling a matrix for use with the {{#crossLink "ColorMatrixFilter"}}{{/crossLink}}. + * Most methods return the instance to facilitate chained calls. + * + *

      Example

      + * + * myColorMatrix.adjustHue(20).adjustBrightness(50); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for an example of how to apply filters, or {{#crossLink "ColorMatrixFilter"}}{{/crossLink}} + * for an example of how to use ColorMatrix to change a DisplayObject's color. + * @class ColorMatrix + * @param {Number} brightness + * @param {Number} contrast + * @param {Number} saturation + * @param {Number} hue + * @constructor + **/ + function ColorMatrix(brightness, contrast, saturation, hue) { + this.setColor(brightness, contrast, saturation, hue); + } + var p = ColorMatrix.prototype; + + /** + * REMOVED. Removed in favor of using `MySuperClass_constructor`. + * See {{#crossLink "Utility Methods/extend"}}{{/crossLink}} and {{#crossLink "Utility Methods/promote"}}{{/crossLink}} + * for details. + * + * There is an inheritance tutorial distributed with EaselJS in /tutorials/Inheritance. + * + * @method initialize + * @protected + * @deprecated + */ + // p.initialize = function() {}; // searchable for devs wondering where it is. + + +// constants: + /** + * Array of delta values for contrast calculations. + * @property DELTA_INDEX + * @type Array + * @protected + * @static + **/ + ColorMatrix.DELTA_INDEX = [ + 0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11, + 0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24, + 0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42, + 0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68, + 0.71, 0.74, 0.77, 0.80, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98, + 1.0, 1.06, 1.12, 1.18, 1.24, 1.30, 1.36, 1.42, 1.48, 1.54, + 1.60, 1.66, 1.72, 1.78, 1.84, 1.90, 1.96, 2.0, 2.12, 2.25, + 2.37, 2.50, 2.62, 2.75, 2.87, 3.0, 3.2, 3.4, 3.6, 3.8, + 4.0, 4.3, 4.7, 4.9, 5.0, 5.5, 6.0, 6.5, 6.8, 7.0, + 7.3, 7.5, 7.8, 8.0, 8.4, 8.7, 9.0, 9.4, 9.6, 9.8, + 10.0 + ]; + + /** + * Identity matrix values. + * @property IDENTITY_MATRIX + * @type Array + * @protected + * @static + **/ + ColorMatrix.IDENTITY_MATRIX = [ + 1,0,0,0,0, + 0,1,0,0,0, + 0,0,1,0,0, + 0,0,0,1,0, + 0,0,0,0,1 + ]; + + /** + * The constant length of a color matrix. + * @property LENGTH + * @type Number + * @protected + * @static + **/ + ColorMatrix.LENGTH = ColorMatrix.IDENTITY_MATRIX.length; + + +// public methods: + /** + * Resets the instance with the specified values. + * @method setColor + * @param {Number} brightness + * @param {Number} contrast + * @param {Number} saturation + * @param {Number} hue + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + */ + p.setColor = function(brightness,contrast,saturation,hue) { + return this.reset().adjustColor(brightness,contrast,saturation,hue); + }; + + /** + * Resets the matrix to identity values. + * @method reset + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + */ + p.reset = function() { + return this.copy(ColorMatrix.IDENTITY_MATRIX); + }; + + /** + * Shortcut method to adjust brightness, contrast, saturation and hue. + * Equivalent to calling adjustHue(hue), adjustContrast(contrast), + * adjustBrightness(brightness), adjustSaturation(saturation), in that order. + * @method adjustColor + * @param {Number} brightness + * @param {Number} contrast + * @param {Number} saturation + * @param {Number} hue + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustColor = function(brightness,contrast,saturation,hue) { + this.adjustHue(hue); + this.adjustContrast(contrast); + this.adjustBrightness(brightness); + return this.adjustSaturation(saturation); + }; + + /** + * Adjusts the brightness of pixel color by adding the specified value to the red, green and blue channels. + * Positive values will make the image brighter, negative values will make it darker. + * @method adjustBrightness + * @param {Number} value A value between -255 & 255 that will be added to the RGB channels. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustBrightness = function(value) { + if (value == 0 || isNaN(value)) { return this; } + value = this._cleanValue(value,255); + this._multiplyMatrix([ + 1,0,0,0,value, + 0,1,0,0,value, + 0,0,1,0,value, + 0,0,0,1,0, + 0,0,0,0,1 + ]); + return this; + }; + + /** + * Adjusts the contrast of pixel color. + * Positive values will increase contrast, negative values will decrease contrast. + * @method adjustContrast + * @param {Number} value A value between -100 & 100. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustContrast = function(value) { + if (value == 0 || isNaN(value)) { return this; } + value = this._cleanValue(value,100); + var x; + if (value<0) { + x = 127+value/100*127; + } else { + x = value%1; + if (x == 0) { + x = ColorMatrix.DELTA_INDEX[value]; + } else { + x = ColorMatrix.DELTA_INDEX[(value<<0)]*(1-x)+ColorMatrix.DELTA_INDEX[(value<<0)+1]*x; // use linear interpolation for more granularity. + } + x = x*127+127; + } + this._multiplyMatrix([ + x/127,0,0,0,0.5*(127-x), + 0,x/127,0,0,0.5*(127-x), + 0,0,x/127,0,0.5*(127-x), + 0,0,0,1,0, + 0,0,0,0,1 + ]); + return this; + }; + + /** + * Adjusts the color saturation of the pixel. + * Positive values will increase saturation, negative values will decrease saturation (trend towards greyscale). + * @method adjustSaturation + * @param {Number} value A value between -100 & 100. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustSaturation = function(value) { + if (value == 0 || isNaN(value)) { return this; } + value = this._cleanValue(value,100); + var x = 1+((value > 0) ? 3*value/100 : value/100); + var lumR = 0.3086; + var lumG = 0.6094; + var lumB = 0.0820; + this._multiplyMatrix([ + lumR*(1-x)+x,lumG*(1-x),lumB*(1-x),0,0, + lumR*(1-x),lumG*(1-x)+x,lumB*(1-x),0,0, + lumR*(1-x),lumG*(1-x),lumB*(1-x)+x,0,0, + 0,0,0,1,0, + 0,0,0,0,1 + ]); + return this; + }; + + + /** + * Adjusts the hue of the pixel color. + * @method adjustHue + * @param {Number} value A value between -180 & 180. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.adjustHue = function(value) { + if (value == 0 || isNaN(value)) { return this; } + value = this._cleanValue(value,180)/180*Math.PI; + var cosVal = Math.cos(value); + var sinVal = Math.sin(value); + var lumR = 0.213; + var lumG = 0.715; + var lumB = 0.072; + this._multiplyMatrix([ + lumR+cosVal*(1-lumR)+sinVal*(-lumR),lumG+cosVal*(-lumG)+sinVal*(-lumG),lumB+cosVal*(-lumB)+sinVal*(1-lumB),0,0, + lumR+cosVal*(-lumR)+sinVal*(0.143),lumG+cosVal*(1-lumG)+sinVal*(0.140),lumB+cosVal*(-lumB)+sinVal*(-0.283),0,0, + lumR+cosVal*(-lumR)+sinVal*(-(1-lumR)),lumG+cosVal*(-lumG)+sinVal*(lumG),lumB+cosVal*(1-lumB)+sinVal*(lumB),0,0, + 0,0,0,1,0, + 0,0,0,0,1 + ]); + return this; + }; + + /** + * Concatenates (multiplies) the specified matrix with this one. + * @method concat + * @param {Array} matrix An array or ColorMatrix instance. + * @return {ColorMatrix} The ColorMatrix instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.concat = function(matrix) { + matrix = this._fixMatrix(matrix); + if (matrix.length != ColorMatrix.LENGTH) { return this; } + this._multiplyMatrix(matrix); + return this; + }; + + /** + * Returns a clone of this ColorMatrix. + * @method clone + * @return {ColorMatrix} A clone of this ColorMatrix. + **/ + p.clone = function() { + return (new ColorMatrix()).copy(this); + }; + + /** + * Return a length 25 (5x5) array instance containing this matrix's values. + * @method toArray + * @return {Array} An array holding this matrix's values. + **/ + p.toArray = function() { + var arr = []; + for (var i= 0, l=ColorMatrix.LENGTH; i ColorMatrix.LENGTH) { + matrix = matrix.slice(0,ColorMatrix.LENGTH); + } + return matrix; + }; + + + createjs.ColorMatrix = ColorMatrix; }()); //############################################################################## // ColorMatrixFilter.js //############################################################################## -this.createjs = this.createjs||{}; - -(function() { - "use strict"; - - -// constructor: - /** - * Allows you to carry out complex color operations such as modifying saturation, brightness, or inverting. See the - * {{#crossLink "ColorMatrix"}}{{/crossLink}} for more information on changing colors. For an easier color transform, - * consider the {{#crossLink "ColorFilter"}}{{/crossLink}}. - * - *

      Example

      - * This example creates a red circle, inverts its hue, and then saturates it to brighten it up. - * - * var shape = new createjs.Shape().set({x:100,y:100}); - * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); - * - * var matrix = new createjs.ColorMatrix().adjustHue(180).adjustSaturation(100); - * shape.filters = [ - * new createjs.ColorMatrixFilter(matrix) - * ]; - * - * shape.cache(-50, -50, 100, 100); - * - * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. - * @class ColorMatrixFilter - * @constructor - * @extends Filter - * @param {Array | ColorMatrix} matrix A 4x5 matrix describing the color operation to perform. See also the {{#crossLink "ColorMatrix"}}{{/crossLink}} - * class. - **/ - function ColorMatrixFilter(matrix) { - - - // public properties: - /** - * A 4x5 matrix describing the color operation to perform. See also the {{#crossLink "ColorMatrix"}}{{/crossLink}} - * @property matrix - * @type Array | ColorMatrix - **/ - this.matrix = matrix; - } - var p = createjs.extend(ColorMatrixFilter, createjs.Filter); - - // TODO: deprecated - // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. - - -// public methods: - /** docced in super class **/ - p.toString = function() { - return "[ColorMatrixFilter]"; - }; - - /** docced in super class **/ - p.clone = function() { - return new ColorMatrixFilter(this.matrix); - }; - -// private methods: - /** docced in super class **/ - p._applyFilter = function(imageData) { - var data = imageData.data; - var l = data.length; - var r,g,b,a; - var mtx = this.matrix; - var m0 = mtx[0], m1 = mtx[1], m2 = mtx[2], m3 = mtx[3], m4 = mtx[4]; - var m5 = mtx[5], m6 = mtx[6], m7 = mtx[7], m8 = mtx[8], m9 = mtx[9]; - var m10 = mtx[10], m11 = mtx[11], m12 = mtx[12], m13 = mtx[13], m14 = mtx[14]; - var m15 = mtx[15], m16 = mtx[16], m17 = mtx[17], m18 = mtx[18], m19 = mtx[19]; - - for (var i=0; iExample + * This example creates a red circle, inverts its hue, and then saturates it to brighten it up. + * + * var shape = new createjs.Shape().set({x:100,y:100}); + * shape.graphics.beginFill("#ff0000").drawCircle(0,0,50); + * + * var matrix = new createjs.ColorMatrix().adjustHue(180).adjustSaturation(100); + * shape.filters = [ + * new createjs.ColorMatrixFilter(matrix) + * ]; + * + * shape.cache(-50, -50, 100, 100); + * + * See {{#crossLink "Filter"}}{{/crossLink}} for an more information on applying filters. + * @class ColorMatrixFilter + * @constructor + * @extends Filter + * @param {Array | ColorMatrix} matrix A 4x5 matrix describing the color operation to perform. See also the {{#crossLink "ColorMatrix"}}{{/crossLink}} + * class. + **/ + function ColorMatrixFilter(matrix) { + + + // public properties: + /** + * A 4x5 matrix describing the color operation to perform. See also the {{#crossLink "ColorMatrix"}}{{/crossLink}} + * @property matrix + * @type Array | ColorMatrix + **/ + this.matrix = matrix; + } + var p = createjs.extend(ColorMatrixFilter, createjs.Filter); + + // TODO: deprecated + // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details. + + +// public methods: + /** docced in super class **/ + p.toString = function() { + return "[ColorMatrixFilter]"; + }; + + /** docced in super class **/ + p.clone = function() { + return new ColorMatrixFilter(this.matrix); + }; + +// private methods: + /** docced in super class **/ + p._applyFilter = function(imageData) { + var data = imageData.data; + var l = data.length; + var r,g,b,a; + var mtx = this.matrix; + var m0 = mtx[0], m1 = mtx[1], m2 = mtx[2], m3 = mtx[3], m4 = mtx[4]; + var m5 = mtx[5], m6 = mtx[6], m7 = mtx[7], m8 = mtx[8], m9 = mtx[9]; + var m10 = mtx[10], m11 = mtx[11], m12 = mtx[12], m13 = mtx[13], m14 = mtx[14]; + var m15 = mtx[15], m16 = mtx[16], m17 = mtx[17], m18 = mtx[18], m19 = mtx[19]; + + for (var i=0; iExample - * - * var stage = new createjs.Stage("canvasId"); - * createjs.Touch.enable(stage); - * - * Note: It is important to disable Touch on a stage that you are no longer using: - * - * createjs.Touch.disable(stage); - * - * @class Touch - * @static - **/ - function Touch() { - throw "Touch cannot be instantiated"; - } - - -// public static methods: - /** - * Returns `true` if touch is supported in the current browser. - * @method isSupported - * @return {Boolean} Indicates whether touch is supported in the current browser. - * @static - **/ - Touch.isSupported = function() { - return !!(('ontouchstart' in window) // iOS & Android - || (window.navigator['msPointerEnabled'] && window.navigator['msMaxTouchPoints'] > 0) // IE10 - || (window.navigator['pointerEnabled'] && window.navigator['maxTouchPoints'] > 0)); // IE11+ - }; - - /** - * Enables touch interaction for the specified EaselJS {{#crossLink "Stage"}}{{/crossLink}}. Currently supports iOS - * (and compatible browsers, such as modern Android browsers), and IE10/11. Supports both single touch and - * multi-touch modes. Extends the EaselJS {{#crossLink "MouseEvent"}}{{/crossLink}} model, but without support for - * double click or over/out events. See the MouseEvent {{#crossLink "MouseEvent/pointerId:property"}}{{/crossLink}} - * for more information. - * @method enable - * @param {Stage} stage The {{#crossLink "Stage"}}{{/crossLink}} to enable touch on. - * @param {Boolean} [singleTouch=false] If `true`, only a single touch will be active at a time. - * @param {Boolean} [allowDefault=false] If `true`, then default gesture actions (ex. scrolling, zooming) will be - * allowed when the user is interacting with the target canvas. - * @return {Boolean} Returns `true` if touch was successfully enabled on the target stage. - * @static - **/ - Touch.enable = function(stage, singleTouch, allowDefault) { - if (!stage || !stage.canvas || !Touch.isSupported()) { return false; } - if (stage.__touch) { return true; } - - // inject required properties on stage: - stage.__touch = {pointers:{}, multitouch:!singleTouch, preventDefault:!allowDefault, count:0}; - - // note that in the future we may need to disable the standard mouse event model before adding - // these to prevent duplicate calls. It doesn't seem to be an issue with iOS devices though. - if ('ontouchstart' in window) { Touch._IOS_enable(stage); } - else if (window.navigator['msPointerEnabled'] || window.navigator["pointerEnabled"]) { Touch._IE_enable(stage); } - return true; - }; - - /** - * Removes all listeners that were set up when calling `Touch.enable()` on a stage. - * @method disable - * @param {Stage} stage The {{#crossLink "Stage"}}{{/crossLink}} to disable touch on. - * @static - **/ - Touch.disable = function(stage) { - if (!stage) { return; } - if ('ontouchstart' in window) { Touch._IOS_disable(stage); } - else if (window.navigator['msPointerEnabled'] || window.navigator["pointerEnabled"]) { Touch._IE_disable(stage); } - - delete stage.__touch; - }; - - -// Private static methods: - /** - * @method _IOS_enable - * @protected - * @param {Stage} stage - * @static - **/ - Touch._IOS_enable = function(stage) { - var canvas = stage.canvas; - var f = stage.__touch.f = function(e) { Touch._IOS_handleEvent(stage,e); }; - canvas.addEventListener("touchstart", f, false); - canvas.addEventListener("touchmove", f, false); - canvas.addEventListener("touchend", f, false); - canvas.addEventListener("touchcancel", f, false); - }; - - /** - * @method _IOS_disable - * @protected - * @param {Stage} stage - * @static - **/ - Touch._IOS_disable = function(stage) { - var canvas = stage.canvas; - if (!canvas) { return; } - var f = stage.__touch.f; - canvas.removeEventListener("touchstart", f, false); - canvas.removeEventListener("touchmove", f, false); - canvas.removeEventListener("touchend", f, false); - canvas.removeEventListener("touchcancel", f, false); - }; - - /** - * @method _IOS_handleEvent - * @param {Stage} stage - * @param {Object} e The event to handle - * @protected - * @static - **/ - Touch._IOS_handleEvent = function(stage, e) { - if (!stage) { return; } - if (stage.__touch.preventDefault) { e.preventDefault&&e.preventDefault(); } - var touches = e.changedTouches; - var type = e.type; - for (var i= 0,l=touches.length; iExample + * + * var stage = new createjs.Stage("canvasId"); + * createjs.Touch.enable(stage); + * + * Note: It is important to disable Touch on a stage that you are no longer using: + * + * createjs.Touch.disable(stage); + * + * @class Touch + * @static + **/ + function Touch() { + throw "Touch cannot be instantiated"; + } + + +// public static methods: + /** + * Returns `true` if touch is supported in the current browser. + * @method isSupported + * @return {Boolean} Indicates whether touch is supported in the current browser. + * @static + **/ + Touch.isSupported = function() { + return !!(('ontouchstart' in window) // iOS & Android + || (window.navigator['msPointerEnabled'] && window.navigator['msMaxTouchPoints'] > 0) // IE10 + || (window.navigator['pointerEnabled'] && window.navigator['maxTouchPoints'] > 0)); // IE11+ + }; + + /** + * Enables touch interaction for the specified EaselJS {{#crossLink "Stage"}}{{/crossLink}}. Currently supports iOS + * (and compatible browsers, such as modern Android browsers), and IE10/11. Supports both single touch and + * multi-touch modes. Extends the EaselJS {{#crossLink "MouseEvent"}}{{/crossLink}} model, but without support for + * double click or over/out events. See the MouseEvent {{#crossLink "MouseEvent/pointerId:property"}}{{/crossLink}} + * for more information. + * @method enable + * @param {Stage} stage The {{#crossLink "Stage"}}{{/crossLink}} to enable touch on. + * @param {Boolean} [singleTouch=false] If `true`, only a single touch will be active at a time. + * @param {Boolean} [allowDefault=false] If `true`, then default gesture actions (ex. scrolling, zooming) will be + * allowed when the user is interacting with the target canvas. + * @return {Boolean} Returns `true` if touch was successfully enabled on the target stage. + * @static + **/ + Touch.enable = function(stage, singleTouch, allowDefault) { + if (!stage || !stage.canvas || !Touch.isSupported()) { return false; } + if (stage.__touch) { return true; } + + // inject required properties on stage: + stage.__touch = {pointers:{}, multitouch:!singleTouch, preventDefault:!allowDefault, count:0}; + + // note that in the future we may need to disable the standard mouse event model before adding + // these to prevent duplicate calls. It doesn't seem to be an issue with iOS devices though. + if ('ontouchstart' in window) { Touch._IOS_enable(stage); } + else if (window.navigator['msPointerEnabled'] || window.navigator["pointerEnabled"]) { Touch._IE_enable(stage); } + return true; + }; + + /** + * Removes all listeners that were set up when calling `Touch.enable()` on a stage. + * @method disable + * @param {Stage} stage The {{#crossLink "Stage"}}{{/crossLink}} to disable touch on. + * @static + **/ + Touch.disable = function(stage) { + if (!stage) { return; } + if ('ontouchstart' in window) { Touch._IOS_disable(stage); } + else if (window.navigator['msPointerEnabled'] || window.navigator["pointerEnabled"]) { Touch._IE_disable(stage); } + + delete stage.__touch; + }; + + +// Private static methods: + /** + * @method _IOS_enable + * @protected + * @param {Stage} stage + * @static + **/ + Touch._IOS_enable = function(stage) { + var canvas = stage.canvas; + var f = stage.__touch.f = function(e) { Touch._IOS_handleEvent(stage,e); }; + canvas.addEventListener("touchstart", f, false); + canvas.addEventListener("touchmove", f, false); + canvas.addEventListener("touchend", f, false); + canvas.addEventListener("touchcancel", f, false); + }; + + /** + * @method _IOS_disable + * @protected + * @param {Stage} stage + * @static + **/ + Touch._IOS_disable = function(stage) { + var canvas = stage.canvas; + if (!canvas) { return; } + var f = stage.__touch.f; + canvas.removeEventListener("touchstart", f, false); + canvas.removeEventListener("touchmove", f, false); + canvas.removeEventListener("touchend", f, false); + canvas.removeEventListener("touchcancel", f, false); + }; + + /** + * @method _IOS_handleEvent + * @param {Stage} stage + * @param {Object} e The event to handle + * @protected + * @static + **/ + Touch._IOS_handleEvent = function(stage, e) { + if (!stage) { return; } + if (stage.__touch.preventDefault) { e.preventDefault&&e.preventDefault(); } + var touches = e.changedTouches; + var type = e.type; + for (var i= 0,l=touches.length; ic;c++)if(b===a[c])return c;return-1},this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c){this.type=a,this.target=null,this.currentTarget=null,this.eventPhase=0,this.bubbles=!!b,this.cancelable=!!c,this.timeStamp=(new Date).getTime(),this.defaultPrevented=!1,this.propagationStopped=!1,this.immediatePropagationStopped=!1,this.removed=!1}var b=a.prototype;b.preventDefault=function(){this.defaultPrevented=this.cancelable&&!0},b.stopPropagation=function(){this.propagationStopped=!0},b.stopImmediatePropagation=function(){this.immediatePropagationStopped=this.propagationStopped=!0},b.remove=function(){this.removed=!0},b.clone=function(){return new a(this.type,this.bubbles,this.cancelable)},b.set=function(a){for(var b in a)this[b]=a[b];return this},b.toString=function(){return"[Event (type="+this.type+")]"},createjs.Event=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this._listeners=null,this._captureListeners=null}var b=a.prototype;a.initialize=function(a){a.addEventListener=b.addEventListener,a.on=b.on,a.removeEventListener=a.off=b.removeEventListener,a.removeAllEventListeners=b.removeAllEventListeners,a.hasEventListener=b.hasEventListener,a.dispatchEvent=b.dispatchEvent,a._dispatchEvent=b._dispatchEvent,a.willTrigger=b.willTrigger},b.addEventListener=function(a,b,c){var d;d=c?this._captureListeners=this._captureListeners||{}:this._listeners=this._listeners||{};var e=d[a];return e&&this.removeEventListener(a,b,c),e=d[a],e?e.push(b):d[a]=[b],b},b.on=function(a,b,c,d,e,f){return b.handleEvent&&(c=c||b,b=b.handleEvent),c=c||this,this.addEventListener(a,function(a){b.call(c,a,e),d&&a.remove()},f)},b.removeEventListener=function(a,b,c){var d=c?this._captureListeners:this._listeners;if(d){var e=d[a];if(e)for(var f=0,g=e.length;g>f;f++)if(e[f]==b){1==g?delete d[a]:e.splice(f,1);break}}},b.off=b.removeEventListener,b.removeAllEventListeners=function(a){a?(this._listeners&&delete this._listeners[a],this._captureListeners&&delete this._captureListeners[a]):this._listeners=this._captureListeners=null},b.dispatchEvent=function(a,b,c){if("string"==typeof a){var d=this._listeners;if(!(b||d&&d[a]))return!0;a=new createjs.Event(a,b,c)}else a.target&&a.clone&&(a=a.clone());try{a.target=this}catch(e){}if(a.bubbles&&this.parent){for(var f=this,g=[f];f.parent;)g.push(f=f.parent);var h,i=g.length;for(h=i-1;h>=0&&!a.propagationStopped;h--)g[h]._dispatchEvent(a,1+(0==h));for(h=1;i>h&&!a.propagationStopped;h++)g[h]._dispatchEvent(a,3)}else this._dispatchEvent(a,2);return!a.defaultPrevented},b.hasEventListener=function(a){var b=this._listeners,c=this._captureListeners;return!!(b&&b[a]||c&&c[a])},b.willTrigger=function(a){for(var b=this;b;){if(b.hasEventListener(a))return!0;b=b.parent}return!1},b.toString=function(){return"[EventDispatcher]"},b._dispatchEvent=function(a,b){var c,d=1==b?this._captureListeners:this._listeners;if(a&&d){var e=d[a.type];if(!e||!(c=e.length))return;try{a.currentTarget=this}catch(f){}try{a.eventPhase=b}catch(f){}a.removed=!1,e=e.slice();for(var g=0;c>g&&!a.immediatePropagationStopped;g++){var h=e[g];h.handleEvent?h.handleEvent(a):h(a),a.removed&&(this.off(a.type,h,1==b),a.removed=!1)}}},createjs.EventDispatcher=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"Ticker cannot be instantiated."}a.RAF_SYNCHED="synched",a.RAF="raf",a.TIMEOUT="timeout",a.useRAF=!1,a.timingMode=null,a.maxDelta=0,a.paused=!1,a.removeEventListener=null,a.removeAllEventListeners=null,a.dispatchEvent=null,a.hasEventListener=null,a._listeners=null,createjs.EventDispatcher.initialize(a),a._addEventListener=a.addEventListener,a.addEventListener=function(){return!a._inited&&a.init(),a._addEventListener.apply(a,arguments)},a._inited=!1,a._startTime=0,a._pausedTime=0,a._ticks=0,a._pausedTicks=0,a._interval=50,a._lastTime=0,a._times=null,a._tickTimes=null,a._timerId=null,a._raf=!0,a.setInterval=function(b){a._interval=b,a._inited&&a._setupTick()},a.getInterval=function(){return a._interval},a.setFPS=function(b){a.setInterval(1e3/b)},a.getFPS=function(){return 1e3/a._interval};try{Object.defineProperties(a,{interval:{get:a.getInterval,set:a.setInterval},framerate:{get:a.getFPS,set:a.setFPS}})}catch(b){console.log(b)}a.init=function(){a._inited||(a._inited=!0,a._times=[],a._tickTimes=[],a._startTime=a._getTime(),a._times.push(a._lastTime=0),a.interval=a._interval)},a.reset=function(){if(a._raf){var b=window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame;b&&b(a._timerId)}else clearTimeout(a._timerId);a.removeAllEventListeners("tick"),a._timerId=a._times=a._tickTimes=null,a._startTime=a._lastTime=a._ticks=0,a._inited=!1},a.getMeasuredTickTime=function(b){var c=0,d=a._tickTimes;if(!d||d.length<1)return-1;b=Math.min(d.length,b||0|a.getFPS());for(var e=0;b>e;e++)c+=d[e];return c/b},a.getMeasuredFPS=function(b){var c=a._times;return!c||c.length<2?-1:(b=Math.min(c.length-1,b||0|a.getFPS()),1e3/((c[0]-c[b])/b))},a.setPaused=function(b){a.paused=b},a.getPaused=function(){return a.paused},a.getTime=function(b){return a._startTime?a._getTime()-(b?a._pausedTime:0):-1},a.getEventTime=function(b){return a._startTime?(a._lastTime||a._startTime)-(b?a._pausedTime:0):-1},a.getTicks=function(b){return a._ticks-(b?a._pausedTicks:0)},a._handleSynch=function(){a._timerId=null,a._setupTick(),a._getTime()-a._lastTime>=.97*(a._interval-1)&&a._tick()},a._handleRAF=function(){a._timerId=null,a._setupTick(),a._tick()},a._handleTimeout=function(){a._timerId=null,a._setupTick(),a._tick()},a._setupTick=function(){if(null==a._timerId){var b=a.timingMode||a.useRAF&&a.RAF_SYNCHED;if(b==a.RAF_SYNCHED||b==a.RAF){var c=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame;if(c)return a._timerId=c(b==a.RAF?a._handleRAF:a._handleSynch),void(a._raf=!0)}a._raf=!1,a._timerId=setTimeout(a._handleTimeout,a._interval)}},a._tick=function(){var b=a.paused,c=a._getTime(),d=c-a._lastTime;if(a._lastTime=c,a._ticks++,b&&(a._pausedTicks++,a._pausedTime+=d),a.hasEventListener("tick")){var e=new createjs.Event("tick"),f=a.maxDelta;e.delta=f&&d>f?f:d,e.paused=b,e.time=c,e.runTime=c-a._pausedTime,a.dispatchEvent(e)}for(a._tickTimes.unshift(a._getTime()-c);a._tickTimes.length>100;)a._tickTimes.pop();for(a._times.unshift(c);a._times.length>100;)a._times.pop()};var c=window.performance&&(performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow);a._getTime=function(){return(c&&c.call(performance)||(new Date).getTime())-a._startTime},createjs.Ticker=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"UID cannot be instantiated"}a._nextID=0,a.get=function(){return a._nextID++},createjs.UID=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k){this.Event_constructor(a,b,c),this.stageX=d,this.stageY=e,this.rawX=null==i?d:i,this.rawY=null==j?e:j,this.nativeEvent=f,this.pointerID=g,this.primary=!!h,this.relatedTarget=k}var b=createjs.extend(a,createjs.Event);b._get_localX=function(){return this.currentTarget.globalToLocal(this.rawX,this.rawY).x},b._get_localY=function(){return this.currentTarget.globalToLocal(this.rawX,this.rawY).y},b._get_isTouch=function(){return-1!==this.pointerID};try{Object.defineProperties(b,{localX:{get:b._get_localX},localY:{get:b._get_localY},isTouch:{get:b._get_isTouch}})}catch(c){}b.clone=function(){return new a(this.type,this.bubbles,this.cancelable,this.stageX,this.stageY,this.nativeEvent,this.pointerID,this.primary,this.rawX,this.rawY)},b.toString=function(){return"[MouseEvent (type="+this.type+" stageX="+this.stageX+" stageY="+this.stageY+")]"},createjs.MouseEvent=createjs.promote(a,"Event")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f){this.setValues(a,b,c,d,e,f)}var b=a.prototype;a.DEG_TO_RAD=Math.PI/180,a.identity=null,b.setValues=function(a,b,c,d,e,f){return this.a=null==a?1:a,this.b=b||0,this.c=c||0,this.d=null==d?1:d,this.tx=e||0,this.ty=f||0,this},b.append=function(a,b,c,d,e,f){var g=this.a,h=this.b,i=this.c,j=this.d;return(1!=a||0!=b||0!=c||1!=d)&&(this.a=g*a+i*b,this.b=h*a+j*b,this.c=g*c+i*d,this.d=h*c+j*d),this.tx=g*e+i*f+this.tx,this.ty=h*e+j*f+this.ty,this},b.prepend=function(a,b,c,d,e,f){var g=this.a,h=this.c,i=this.tx;return this.a=a*g+c*this.b,this.b=b*g+d*this.b,this.c=a*h+c*this.d,this.d=b*h+d*this.d,this.tx=a*i+c*this.ty+e,this.ty=b*i+d*this.ty+f,this},b.appendMatrix=function(a){return this.append(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.prependMatrix=function(a){return this.prepend(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.appendTransform=function(b,c,d,e,f,g,h,i,j){if(f%360)var k=f*a.DEG_TO_RAD,l=Math.cos(k),m=Math.sin(k);else l=1,m=0;return g||h?(g*=a.DEG_TO_RAD,h*=a.DEG_TO_RAD,this.append(Math.cos(h),Math.sin(h),-Math.sin(g),Math.cos(g),b,c),this.append(l*d,m*d,-m*e,l*e,0,0)):this.append(l*d,m*d,-m*e,l*e,b,c),(i||j)&&(this.tx-=i*this.a+j*this.c,this.ty-=i*this.b+j*this.d),this},b.prependTransform=function(b,c,d,e,f,g,h,i,j){if(f%360)var k=f*a.DEG_TO_RAD,l=Math.cos(k),m=Math.sin(k);else l=1,m=0;return(i||j)&&(this.tx-=i,this.ty-=j),g||h?(g*=a.DEG_TO_RAD,h*=a.DEG_TO_RAD,this.prepend(l*d,m*d,-m*e,l*e,0,0),this.prepend(Math.cos(h),Math.sin(h),-Math.sin(g),Math.cos(g),b,c)):this.prepend(l*d,m*d,-m*e,l*e,b,c),this},b.rotate=function(b){b*=a.DEG_TO_RAD;var c=Math.cos(b),d=Math.sin(b),e=this.a,f=this.b;return this.a=e*c+this.c*d,this.b=f*c+this.d*d,this.c=-e*d+this.c*c,this.d=-f*d+this.d*c,this},b.skew=function(b,c){return b*=a.DEG_TO_RAD,c*=a.DEG_TO_RAD,this.append(Math.cos(c),Math.sin(c),-Math.sin(b),Math.cos(b),0,0),this},b.scale=function(a,b){return this.a*=a,this.b*=a,this.c*=b,this.d*=b,this},b.translate=function(a,b){return this.tx+=this.a*a+this.c*b,this.ty+=this.b*a+this.d*b,this},b.identity=function(){return this.a=this.d=1,this.b=this.c=this.tx=this.ty=0,this},b.invert=function(){var a=this.a,b=this.b,c=this.c,d=this.d,e=this.tx,f=a*d-b*c;return this.a=d/f,this.b=-b/f,this.c=-c/f,this.d=a/f,this.tx=(c*this.ty-d*e)/f,this.ty=-(a*this.ty-b*e)/f,this},b.isIdentity=function(){return 0===this.tx&&0===this.ty&&1===this.a&&0===this.b&&0===this.c&&1===this.d},b.equals=function(a){return this.tx===a.tx&&this.ty===a.ty&&this.a===a.a&&this.b===a.b&&this.c===a.c&&this.d===a.d},b.transformPoint=function(a,b,c){return c=c||{},c.x=a*this.a+b*this.c+this.tx,c.y=a*this.b+b*this.d+this.ty,c},b.decompose=function(b){null==b&&(b={}),b.x=this.tx,b.y=this.ty,b.scaleX=Math.sqrt(this.a*this.a+this.b*this.b),b.scaleY=Math.sqrt(this.c*this.c+this.d*this.d);var c=Math.atan2(-this.c,this.d),d=Math.atan2(this.b,this.a),e=Math.abs(1-c/d);return 1e-5>e?(b.rotation=d/a.DEG_TO_RAD,this.a<0&&this.d>=0&&(b.rotation+=b.rotation<=0?180:-180),b.skewX=b.skewY=0):(b.skewX=c/a.DEG_TO_RAD,b.skewY=d/a.DEG_TO_RAD),b},b.copy=function(a){return this.setValues(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.clone=function(){return new a(this.a,this.b,this.c,this.d,this.tx,this.ty)},b.toString=function(){return"[Matrix2D (a="+this.a+" b="+this.b+" c="+this.c+" d="+this.d+" tx="+this.tx+" ty="+this.ty+")]"},a.identity=new a,createjs.Matrix2D=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e){this.setValues(a,b,c,d,e)}var b=a.prototype;b.setValues=function(a,b,c,d,e){return this.visible=null==a?!0:!!a,this.alpha=null==b?1:b,this.shadow=c,this.compositeOperation=c,this.matrix=e||this.matrix&&this.matrix.identity()||new createjs.Matrix2D,this},b.append=function(a,b,c,d,e){return this.alpha*=b,this.shadow=c||this.shadow,this.compositeOperation=d||this.compositeOperation,this.visible=this.visible&&a,e&&this.matrix.appendMatrix(e),this},b.prepend=function(a,b,c,d,e){return this.alpha*=b,this.shadow=this.shadow||c,this.compositeOperation=this.compositeOperation||d,this.visible=this.visible&&a,e&&this.matrix.prependMatrix(e),this},b.identity=function(){return this.visible=!0,this.alpha=1,this.shadow=this.compositeOperation=null,this.matrix.identity(),this},b.clone=function(){return new a(this.alpha,this.shadow,this.compositeOperation,this.visible,this.matrix.clone())},createjs.DisplayProps=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.setValues(a,b)}var b=a.prototype;b.setValues=function(a,b){return this.x=a||0,this.y=b||0,this},b.copy=function(a){return this.x=a.x,this.y=a.y,this},b.clone=function(){return new a(this.x,this.y)},b.toString=function(){return"[Point (x="+this.x+" y="+this.y+")]"},createjs.Point=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d){this.setValues(a,b,c,d)}var b=a.prototype;b.setValues=function(a,b,c,d){return this.x=a||0,this.y=b||0,this.width=c||0,this.height=d||0,this},b.extend=function(a,b,c,d){return c=c||0,d=d||0,a+c>this.x+this.width&&(this.width=a+c-this.x),b+d>this.y+this.height&&(this.height=b+d-this.y),a=this.x&&a+c<=this.x+this.width&&b>=this.y&&b+d<=this.y+this.height},b.union=function(a){return this.clone().extend(a.x,a.y,a.width,a.height)},b.intersection=function(b){var c=b.x,d=b.y,e=c+b.width,f=d+b.height;return this.x>c&&(c=this.x),this.y>d&&(d=this.y),this.x+this.width=e||d>=f?null:new a(c,d,e-c,f-d)},b.intersects=function(a){return a.x<=this.x+this.width&&this.x<=a.x+a.width&&a.y<=this.y+this.height&&this.y<=a.y+a.height},b.isEmpty=function(){return this.width<=0||this.height<=0},b.clone=function(){return new a(this.x,this.y,this.width,this.height)},b.toString=function(){return"[Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")]"},createjs.Rectangle=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f,g){a.addEventListener&&(this.target=a,this.overLabel=null==c?"over":c,this.outLabel=null==b?"out":b,this.downLabel=null==d?"down":d,this.play=e,this._isPressed=!1,this._isOver=!1,this._enabled=!1,a.mouseChildren=!1,this.enabled=!0,this.handleEvent({}),f&&(g&&(f.actionsEnabled=!1,f.gotoAndStop&&f.gotoAndStop(g)),a.hitArea=f))}var b=a.prototype;b.setEnabled=function(a){if(a!=this._enabled){var b=this.target;this._enabled=a,a?(b.cursor="pointer",b.addEventListener("rollover",this),b.addEventListener("rollout",this),b.addEventListener("mousedown",this),b.addEventListener("pressup",this),b._reset&&(b.__reset=b._reset,b._reset=this._reset)):(b.cursor=null,b.removeEventListener("rollover",this),b.removeEventListener("rollout",this),b.removeEventListener("mousedown",this),b.removeEventListener("pressup",this),b.__reset&&(b._reset=b.__reset,delete b.__reset))}},b.getEnabled=function(){return this._enabled};try{Object.defineProperties(b,{enabled:{get:b.getEnabled,set:b.setEnabled}})}catch(c){}b.toString=function(){return"[ButtonHelper]"},b.handleEvent=function(a){var b,c=this.target,d=a.type;"mousedown"==d?(this._isPressed=!0,b=this.downLabel):"pressup"==d?(this._isPressed=!1,b=this._isOver?this.overLabel:this.outLabel):"rollover"==d?(this._isOver=!0,b=this._isPressed?this.downLabel:this.overLabel):(this._isOver=!1,b=this._isPressed?this.overLabel:this.outLabel),this.play?c.gotoAndPlay&&c.gotoAndPlay(b):c.gotoAndStop&&c.gotoAndStop(b)},b._reset=function(){var a=this.paused;this.__reset(),this.paused=a},createjs.ButtonHelper=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d){this.color=a||"black",this.offsetX=b||0,this.offsetY=c||0,this.blur=d||0}var b=a.prototype;a.identity=new a("transparent",0,0,0),b.toString=function(){return"[Shadow]"},b.clone=function(){return new a(this.color,this.offsetX,this.offsetY,this.blur)},createjs.Shadow=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.EventDispatcher_constructor(),this.complete=!0,this.framerate=0,this._animations=null,this._frames=null,this._images=null,this._data=null,this._loadCount=0,this._frameHeight=0,this._frameWidth=0,this._numFrames=0,this._regX=0,this._regY=0,this._spacing=0,this._margin=0,this._parseData(a)}var b=createjs.extend(a,createjs.EventDispatcher);b.getAnimations=function(){return this._animations.slice()};try{Object.defineProperties(b,{animations:{get:b.getAnimations}})}catch(c){}b.getNumFrames=function(a){if(null==a)return this._frames?this._frames.length:this._numFrames||0;var b=this._data[a];return null==b?0:b.frames.length},b.getAnimation=function(a){return this._data[a]},b.getFrame=function(a){var b;return this._frames&&(b=this._frames[a])?b:null},b.getFrameBounds=function(a,b){var c=this.getFrame(a);return c?(b||new createjs.Rectangle).setValues(-c.regX,-c.regY,c.rect.width,c.rect.height):null},b.toString=function(){return"[SpriteSheet]"},b.clone=function(){throw"SpriteSheet cannot be cloned."},b._parseData=function(a){var b,c,d,e;if(null!=a){if(this.framerate=a.framerate||0,a.images&&(c=a.images.length)>0)for(e=this._images=[],b=0;c>b;b++){var f=a.images[b];if("string"==typeof f){var g=f;f=document.createElement("img"),f.src=g}e.push(f),f.getContext||f.naturalWidth||(this._loadCount++,this.complete=!1,function(a){f.onload=function(){a._handleImageLoad()}}(this))}if(null==a.frames);else if(a.frames instanceof Array)for(this._frames=[],e=a.frames,b=0,c=e.length;c>b;b++){var h=e[b];this._frames.push({image:this._images[h[4]?h[4]:0],rect:new createjs.Rectangle(h[0],h[1],h[2],h[3]),regX:h[5]||0,regY:h[6]||0})}else d=a.frames,this._frameWidth=d.width,this._frameHeight=d.height,this._regX=d.regX||0,this._regY=d.regY||0,this._spacing=d.spacing||0,this._margin=d.margin||0,this._numFrames=d.count,0==this._loadCount&&this._calculateFrames();if(this._animations=[],null!=(d=a.animations)){this._data={};var i;for(i in d){var j={name:i},k=d[i];if("number"==typeof k)e=j.frames=[k];else if(k instanceof Array)if(1==k.length)j.frames=[k[0]];else for(j.speed=k[3],j.next=k[2],e=j.frames=[],b=k[0];b<=k[1];b++)e.push(b);else{j.speed=k.speed,j.next=k.next;var l=k.frames;e=j.frames="number"==typeof l?[l]:l.slice(0)}(j.next===!0||void 0===j.next)&&(j.next=i),(j.next===!1||e.length<2&&j.next==i)&&(j.next=null),j.speed||(j.speed=1),this._animations.push(i),this._data[i]=j}}}},b._handleImageLoad=function(){0==--this._loadCount&&(this._calculateFrames(),this.complete=!0,this.dispatchEvent("complete"))},b._calculateFrames=function(){if(!this._frames&&0!=this._frameWidth){this._frames=[];var a=this._numFrames||1e5,b=0,c=this._frameWidth,d=this._frameHeight,e=this._spacing,f=this._margin;a:for(var g=0,h=this._images;g=l;){for(var m=f;j-f-c>=m;){if(b>=a)break a;b++,this._frames.push({image:i,rect:new createjs.Rectangle(m,l,c,d),regX:this._regX,regY:this._regY}),m+=c+e}l+=d+e}this._numFrames=b}},createjs.SpriteSheet=createjs.promote(a,"EventDispatcher")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this.command=null,this._stroke=null,this._strokeStyle=null,this._oldStrokeStyle=null,this._strokeDash=null,this._oldStrokeDash=null,this._strokeIgnoreScale=!1,this._fill=null,this._instructions=[],this._commitIndex=0,this._activeInstructions=[],this._dirty=!1,this._storeIndex=0,this.clear()}var b=a.prototype,c=a;a.getRGB=function(a,b,c,d){return null!=a&&null==c&&(d=b,c=255&a,b=a>>8&255,a=a>>16&255),null==d?"rgb("+a+","+b+","+c+")":"rgba("+a+","+b+","+c+","+d+")"},a.getHSL=function(a,b,c,d){return null==d?"hsl("+a%360+","+b+"%,"+c+"%)":"hsla("+a%360+","+b+"%,"+c+"%,"+d+")"},a.BASE_64={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,a:26,b:27,c:28,d:29,e:30,f:31,g:32,h:33,i:34,j:35,k:36,l:37,m:38,n:39,o:40,p:41,q:42,r:43,s:44,t:45,u:46,v:47,w:48,x:49,y:50,z:51,0:52,1:53,2:54,3:55,4:56,5:57,6:58,7:59,8:60,9:61,"+":62,"/":63},a.STROKE_CAPS_MAP=["butt","round","square"],a.STROKE_JOINTS_MAP=["miter","round","bevel"];var d=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");d.getContext&&(a._ctx=d.getContext("2d"),d.width=d.height=1),b.getInstructions=function(){return this._updateInstructions(),this._instructions};try{Object.defineProperties(b,{instructions:{get:b.getInstructions}})}catch(e){}b.isEmpty=function(){return!(this._instructions.length||this._activeInstructions.length)},b.draw=function(a,b){this._updateInstructions();for(var c=this._instructions,d=this._storeIndex,e=c.length;e>d;d++)c[d].exec(a,b)},b.drawAsPath=function(a){this._updateInstructions();for(var b,c=this._instructions,d=this._storeIndex,e=c.length;e>d;d++)(b=c[d]).path!==!1&&b.exec(a)},b.moveTo=function(a,b){return this.append(new c.MoveTo(a,b),!0)},b.lineTo=function(a,b){return this.append(new c.LineTo(a,b))},b.arcTo=function(a,b,d,e,f){return this.append(new c.ArcTo(a,b,d,e,f))},b.arc=function(a,b,d,e,f,g){return this.append(new c.Arc(a,b,d,e,f,g))},b.quadraticCurveTo=function(a,b,d,e){return this.append(new c.QuadraticCurveTo(a,b,d,e))},b.bezierCurveTo=function(a,b,d,e,f,g){return this.append(new c.BezierCurveTo(a,b,d,e,f,g))},b.rect=function(a,b,d,e){return this.append(new c.Rect(a,b,d,e))},b.closePath=function(){return this._activeInstructions.length?this.append(new c.ClosePath):this},b.clear=function(){return this._instructions.length=this._activeInstructions.length=this._commitIndex=0,this._strokeStyle=this._oldStrokeStyle=this._stroke=this._fill=this._strokeDash=this._oldStrokeDash=null,this._dirty=this._strokeIgnoreScale=!1,this},b.beginFill=function(a){return this._setFill(a?new c.Fill(a):null)},b.beginLinearGradientFill=function(a,b,d,e,f,g){return this._setFill((new c.Fill).linearGradient(a,b,d,e,f,g))},b.beginRadialGradientFill=function(a,b,d,e,f,g,h,i){return this._setFill((new c.Fill).radialGradient(a,b,d,e,f,g,h,i))},b.beginBitmapFill=function(a,b,d){return this._setFill(new c.Fill(null,d).bitmap(a,b))},b.endFill=function(){return this.beginFill()},b.setStrokeStyle=function(a,b,d,e,f){return this._updateInstructions(!0),this._strokeStyle=this.command=new c.StrokeStyle(a,b,d,e,f),this._stroke&&(this._stroke.ignoreScale=f),this._strokeIgnoreScale=f,this},b.setStrokeDash=function(a,b){return this._updateInstructions(!0),this._strokeDash=this.command=new c.StrokeDash(a,b),this},b.beginStroke=function(a){return this._setStroke(a?new c.Stroke(a):null)},b.beginLinearGradientStroke=function(a,b,d,e,f,g){return this._setStroke((new c.Stroke).linearGradient(a,b,d,e,f,g))},b.beginRadialGradientStroke=function(a,b,d,e,f,g,h,i){return this._setStroke((new c.Stroke).radialGradient(a,b,d,e,f,g,h,i))},b.beginBitmapStroke=function(a,b){return this._setStroke((new c.Stroke).bitmap(a,b))},b.endStroke=function(){return this.beginStroke()},b.curveTo=b.quadraticCurveTo,b.drawRect=b.rect,b.drawRoundRect=function(a,b,c,d,e){return this.drawRoundRectComplex(a,b,c,d,e,e,e,e)},b.drawRoundRectComplex=function(a,b,d,e,f,g,h,i){return this.append(new c.RoundRect(a,b,d,e,f,g,h,i))},b.drawCircle=function(a,b,d){return this.append(new c.Circle(a,b,d))},b.drawEllipse=function(a,b,d,e){return this.append(new c.Ellipse(a,b,d,e))},b.drawPolyStar=function(a,b,d,e,f,g){return this.append(new c.PolyStar(a,b,d,e,f,g))},b.append=function(a,b){return this._activeInstructions.push(a),this.command=a,b||(this._dirty=!0),this},b.decodePath=function(b){for(var c=[this.moveTo,this.lineTo,this.quadraticCurveTo,this.bezierCurveTo,this.closePath],d=[2,2,4,6,0],e=0,f=b.length,g=[],h=0,i=0,j=a.BASE_64;f>e;){var k=b.charAt(e),l=j[k],m=l>>3,n=c[m];if(!n||3&l)throw"bad path data (@"+e+"): "+k;var o=d[m];m||(h=i=0),g.length=0,e++;for(var p=(l>>2&1)+2,q=0;o>q;q++){var r=j[b.charAt(e)],s=r>>5?-1:1;r=(31&r)<<6|j[b.charAt(e+1)],3==p&&(r=r<<6|j[b.charAt(e+2)]),r=s*r/10,q%2?h=r+=h:i=r+=i,g[q]=r,e+=p}n.apply(this,g)}return this},b.store=function(){return this._updateInstructions(!0),this._storeIndex=this._instructions.length,this},b.unstore=function(){return this._storeIndex=0,this},b.clone=function(){var b=new a;return b.command=this.command,b._stroke=this._stroke,b._strokeStyle=this._strokeStyle,b._strokeDash=this._strokeDash,b._strokeIgnoreScale=this._strokeIgnoreScale,b._fill=this._fill,b._instructions=this._instructions.slice(),b._commitIndex=this._commitIndex,b._activeInstructions=this._activeInstructions.slice(),b._dirty=this._dirty,b._storeIndex=this._storeIndex,b},b.toString=function(){return"[Graphics]"},b.mt=b.moveTo,b.lt=b.lineTo,b.at=b.arcTo,b.bt=b.bezierCurveTo,b.qt=b.quadraticCurveTo,b.a=b.arc,b.r=b.rect,b.cp=b.closePath,b.c=b.clear,b.f=b.beginFill,b.lf=b.beginLinearGradientFill,b.rf=b.beginRadialGradientFill,b.bf=b.beginBitmapFill,b.ef=b.endFill,b.ss=b.setStrokeStyle,b.sd=b.setStrokeDash,b.s=b.beginStroke,b.ls=b.beginLinearGradientStroke,b.rs=b.beginRadialGradientStroke,b.bs=b.beginBitmapStroke,b.es=b.endStroke,b.dr=b.drawRect,b.rr=b.drawRoundRect,b.rc=b.drawRoundRectComplex,b.dc=b.drawCircle,b.de=b.drawEllipse,b.dp=b.drawPolyStar,b.p=b.decodePath,b._updateInstructions=function(b){var c=this._instructions,d=this._activeInstructions,e=this._commitIndex;if(this._dirty&&d.length){c.length=e,c.push(a.beginCmd);var f=d.length,g=c.length;c.length=g+f;for(var h=0;f>h;h++)c[h+g]=d[h];this._fill&&c.push(this._fill),this._stroke&&(this._strokeDash!==this._oldStrokeDash&&(this._oldStrokeDash=this._strokeDash,c.push(this._strokeDash)),this._strokeStyle!==this._oldStrokeStyle&&(this._oldStrokeStyle=this._strokeStyle,c.push(this._strokeStyle)),c.push(this._stroke)),this._dirty=!1}b&&(d.length=0,this._commitIndex=c.length)},b._setFill=function(a){return this._updateInstructions(!0),this.command=this._fill=a,this},b._setStroke=function(a){return this._updateInstructions(!0),(this.command=this._stroke=a)&&(a.ignoreScale=this._strokeIgnoreScale),this},(c.LineTo=function(a,b){this.x=a,this.y=b}).prototype.exec=function(a){a.lineTo(this.x,this.y)},(c.MoveTo=function(a,b){this.x=a,this.y=b}).prototype.exec=function(a){a.moveTo(this.x,this.y)},(c.ArcTo=function(a,b,c,d,e){this.x1=a,this.y1=b,this.x2=c,this.y2=d,this.radius=e}).prototype.exec=function(a){a.arcTo(this.x1,this.y1,this.x2,this.y2,this.radius)},(c.Arc=function(a,b,c,d,e,f){this.x=a,this.y=b,this.radius=c,this.startAngle=d,this.endAngle=e,this.anticlockwise=!!f}).prototype.exec=function(a){a.arc(this.x,this.y,this.radius,this.startAngle,this.endAngle,this.anticlockwise)},(c.QuadraticCurveTo=function(a,b,c,d){this.cpx=a,this.cpy=b,this.x=c,this.y=d}).prototype.exec=function(a){a.quadraticCurveTo(this.cpx,this.cpy,this.x,this.y)},(c.BezierCurveTo=function(a,b,c,d,e,f){this.cp1x=a,this.cp1y=b,this.cp2x=c,this.cp2y=d,this.x=e,this.y=f}).prototype.exec=function(a){a.bezierCurveTo(this.cp1x,this.cp1y,this.cp2x,this.cp2y,this.x,this.y)},(c.Rect=function(a,b,c,d){this.x=a,this.y=b,this.w=c,this.h=d}).prototype.exec=function(a){a.rect(this.x,this.y,this.w,this.h)},(c.ClosePath=function(){}).prototype.exec=function(a){a.closePath()},(c.BeginPath=function(){}).prototype.exec=function(a){a.beginPath()},b=(c.Fill=function(a,b){this.style=a,this.matrix=b}).prototype,b.exec=function(a){if(this.style){a.fillStyle=this.style;var b=this.matrix;b&&(a.save(),a.transform(b.a,b.b,b.c,b.d,b.tx,b.ty)),a.fill(),b&&a.restore()}},b.linearGradient=function(b,c,d,e,f,g){for(var h=this.style=a._ctx.createLinearGradient(d,e,f,g),i=0,j=b.length;j>i;i++)h.addColorStop(c[i],b[i]);return h.props={colors:b,ratios:c,x0:d,y0:e,x1:f,y1:g,type:"linear"},this},b.radialGradient=function(b,c,d,e,f,g,h,i){for(var j=this.style=a._ctx.createRadialGradient(d,e,f,g,h,i),k=0,l=b.length;l>k;k++)j.addColorStop(c[k],b[k]);return j.props={colors:b,ratios:c,x0:d,y0:e,r0:f,x1:g,y1:h,r1:i,type:"radial"},this},b.bitmap=function(b,c){if(b.naturalWidth||b.getContext||b.readyState>=2){var d=this.style=a._ctx.createPattern(b,c||"");d.props={image:b,repetition:c,type:"bitmap"}}return this},b.path=!1,b=(c.Stroke=function(a,b){this.style=a,this.ignoreScale=b}).prototype,b.exec=function(a){this.style&&(a.strokeStyle=this.style,this.ignoreScale&&(a.save(),a.setTransform(1,0,0,1,0,0)),a.stroke(),this.ignoreScale&&a.restore())},b.linearGradient=c.Fill.prototype.linearGradient,b.radialGradient=c.Fill.prototype.radialGradient,b.bitmap=c.Fill.prototype.bitmap,b.path=!1,b=(c.StrokeStyle=function(a,b,c,d){this.width=a,this.caps=b,this.joints=c,this.miterLimit=d}).prototype,b.exec=function(b){b.lineWidth=null==this.width?"1":this.width,b.lineCap=null==this.caps?"butt":isNaN(this.caps)?this.caps:a.STROKE_CAPS_MAP[this.caps],b.lineJoin=null==this.joints?"miter":isNaN(this.joints)?this.joints:a.STROKE_JOINTS_MAP[this.joints],b.miterLimit=null==this.miterLimit?"10":this.miterLimit},b.path=!1,(c.StrokeDash=function(a,b){this.segments=a,this.offset=b||0}).prototype.exec=function(a){a.setLineDash&&(a.setLineDash(this.segments||c.StrokeDash.EMPTY_SEGMENTS),a.lineDashOffset=this.offset||0)},c.StrokeDash.EMPTY_SEGMENTS=[],(c.RoundRect=function(a,b,c,d,e,f,g,h){this.x=a,this.y=b,this.w=c,this.h=d,this.radiusTL=e,this.radiusTR=f,this.radiusBR=g,this.radiusBL=h}).prototype.exec=function(a){var b=(j>i?i:j)/2,c=0,d=0,e=0,f=0,g=this.x,h=this.y,i=this.w,j=this.h,k=this.radiusTL,l=this.radiusTR,m=this.radiusBR,n=this.radiusBL;0>k&&(k*=c=-1),k>b&&(k=b),0>l&&(l*=d=-1),l>b&&(l=b),0>m&&(m*=e=-1),m>b&&(m=b),0>n&&(n*=f=-1),n>b&&(n=b),a.moveTo(g+i-l,h),a.arcTo(g+i+l*d,h-l*d,g+i,h+l,l),a.lineTo(g+i,h+j-m),a.arcTo(g+i+m*e,h+j+m*e,g+i-m,h+j,m),a.lineTo(g+n,h+j),a.arcTo(g-n*f,h+j+n*f,g,h+j-n,n),a.lineTo(g,h+k),a.arcTo(g-k*c,h-k*c,g+k,h,k),a.closePath()},(c.Circle=function(a,b,c){this.x=a,this.y=b,this.radius=c}).prototype.exec=function(a){a.arc(this.x,this.y,this.radius,0,2*Math.PI)},(c.Ellipse=function(a,b,c,d){this.x=a,this.y=b,this.w=c,this.h=d}).prototype.exec=function(a){var b=this.x,c=this.y,d=this.w,e=this.h,f=.5522848,g=d/2*f,h=e/2*f,i=b+d,j=c+e,k=b+d/2,l=c+e/2;a.moveTo(b,l),a.bezierCurveTo(b,l-h,k-g,c,k,c),a.bezierCurveTo(k+g,c,i,l-h,i,l),a.bezierCurveTo(i,l+h,k+g,j,k,j),a.bezierCurveTo(k-g,j,b,l+h,b,l)},(c.PolyStar=function(a,b,c,d,e,f){this.x=a,this.y=b,this.radius=c,this.sides=d,this.pointSize=e,this.angle=f}).prototype.exec=function(a){var b=this.x,c=this.y,d=this.radius,e=(this.angle||0)/180*Math.PI,f=this.sides,g=1-(this.pointSize||0),h=Math.PI/f;a.moveTo(b+Math.cos(e)*d,c+Math.sin(e)*d);for(var i=0;f>i;i++)e+=h,1!=g&&a.lineTo(b+Math.cos(e)*d*g,c+Math.sin(e)*d*g),e+=h,a.lineTo(b+Math.cos(e)*d,c+Math.sin(e)*d);a.closePath()},a.beginCmd=new c.BeginPath,createjs.Graphics=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this.EventDispatcher_constructor(),this.alpha=1,this.cacheCanvas=null,this.cacheID=0,this.id=createjs.UID.get(),this.mouseEnabled=!0,this.tickEnabled=!0,this.name=null,this.parent=null,this.regX=0,this.regY=0,this.rotation=0,this.scaleX=1,this.scaleY=1,this.skewX=0,this.skewY=0,this.shadow=null,this.visible=!0,this.x=0,this.y=0,this.transformMatrix=null,this.compositeOperation=null,this.snapToPixel=!0,this.filters=null,this.mask=null,this.hitArea=null,this.cursor=null,this._cacheOffsetX=0,this._cacheOffsetY=0,this._filterOffsetX=0,this._filterOffsetY=0,this._cacheScale=1,this._cacheDataURLID=0,this._cacheDataURL=null,this._props=new createjs.DisplayProps,this._rectangle=new createjs.Rectangle,this._bounds=null -}var b=createjs.extend(a,createjs.EventDispatcher);a._MOUSE_EVENTS=["click","dblclick","mousedown","mouseout","mouseover","pressmove","pressup","rollout","rollover"],a.suppressCrossDomainErrors=!1,a._snapToPixelEnabled=!1;var c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");c.getContext&&(a._hitTestCanvas=c,a._hitTestContext=c.getContext("2d"),c.width=c.height=1),a._nextCacheID=1,b.getStage=function(){for(var a=this,b=createjs.Stage;a.parent;)a=a.parent;return a instanceof b?a:null};try{Object.defineProperties(b,{stage:{get:b.getStage}})}catch(d){}b.isVisible=function(){return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY)},b.draw=function(a,b){var c=this.cacheCanvas;if(b||!c)return!1;var d=this._cacheScale;return a.drawImage(c,this._cacheOffsetX+this._filterOffsetX,this._cacheOffsetY+this._filterOffsetY,c.width/d,c.height/d),!0},b.updateContext=function(b){var c=this,d=c.mask,e=c._props.matrix;d&&d.graphics&&!d.graphics.isEmpty()&&(d.getMatrix(e),b.transform(e.a,e.b,e.c,e.d,e.tx,e.ty),d.graphics.drawAsPath(b),b.clip(),e.invert(),b.transform(e.a,e.b,e.c,e.d,e.tx,e.ty)),this.getMatrix(e);var f=e.tx,g=e.ty;a._snapToPixelEnabled&&c.snapToPixel&&(f=f+(0>f?-.5:.5)|0,g=g+(0>g?-.5:.5)|0),b.transform(e.a,e.b,e.c,e.d,f,g),b.globalAlpha*=c.alpha,c.compositeOperation&&(b.globalCompositeOperation=c.compositeOperation),c.shadow&&this._applyShadow(b,c.shadow)},b.cache=function(a,b,c,d,e){e=e||1,this.cacheCanvas||(this.cacheCanvas=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")),this._cacheWidth=c,this._cacheHeight=d,this._cacheOffsetX=a,this._cacheOffsetY=b,this._cacheScale=e,this.updateCache()},b.updateCache=function(b){var c=this.cacheCanvas;if(!c)throw"cache() must be called before updateCache()";var d=this._cacheScale,e=this._cacheOffsetX*d,f=this._cacheOffsetY*d,g=this._cacheWidth,h=this._cacheHeight,i=c.getContext("2d"),j=this._getFilterBounds();e+=this._filterOffsetX=j.x,f+=this._filterOffsetY=j.y,g=Math.ceil(g*d)+j.width,h=Math.ceil(h*d)+j.height,g!=c.width||h!=c.height?(c.width=g,c.height=h):b||i.clearRect(0,0,g+1,h+1),i.save(),i.globalCompositeOperation=b,i.setTransform(d,0,0,d,-e,-f),this.draw(i,!0),this._applyFilters(),i.restore(),this.cacheID=a._nextCacheID++},b.uncache=function(){this._cacheDataURL=this.cacheCanvas=null,this.cacheID=this._cacheOffsetX=this._cacheOffsetY=this._filterOffsetX=this._filterOffsetY=0,this._cacheScale=1},b.getCacheDataURL=function(){return this.cacheCanvas?(this.cacheID!=this._cacheDataURLID&&(this._cacheDataURL=this.cacheCanvas.toDataURL()),this._cacheDataURL):null},b.localToGlobal=function(a,b,c){return this.getConcatenatedMatrix(this._props.matrix).transformPoint(a,b,c||new createjs.Point)},b.globalToLocal=function(a,b,c){return this.getConcatenatedMatrix(this._props.matrix).invert().transformPoint(a,b,c||new createjs.Point)},b.localToLocal=function(a,b,c,d){return d=this.localToGlobal(a,b,d),c.globalToLocal(d.x,d.y,d)},b.setTransform=function(a,b,c,d,e,f,g,h,i){return this.x=a||0,this.y=b||0,this.scaleX=null==c?1:c,this.scaleY=null==d?1:d,this.rotation=e||0,this.skewX=f||0,this.skewY=g||0,this.regX=h||0,this.regY=i||0,this},b.getMatrix=function(a){var b=this,c=a&&a.identity()||new createjs.Matrix2D;return b.transformMatrix?c.copy(b.transformMatrix):c.appendTransform(b.x,b.y,b.scaleX,b.scaleY,b.rotation,b.skewX,b.skewY,b.regX,b.regY)},b.getConcatenatedMatrix=function(a){for(var b=this,c=this.getMatrix(a);b=b.parent;)c.prependMatrix(b.getMatrix(b._props.matrix));return c},b.getConcatenatedDisplayProps=function(a){a=a?a.identity():new createjs.DisplayProps;var b=this,c=b.getMatrix(a.matrix);do a.prepend(b.visible,b.alpha,b.shadow,b.compositeOperation),b!=this&&c.prependMatrix(b.getMatrix(b._props.matrix));while(b=b.parent);return a},b.hitTest=function(b,c){var d=a._hitTestContext;d.setTransform(1,0,0,1,-b,-c),this.draw(d);var e=this._testHit(d);return d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,2,2),e},b.set=function(a){for(var b in a)this[b]=a[b];return this},b.getBounds=function(){if(this._bounds)return this._rectangle.copy(this._bounds);var a=this.cacheCanvas;if(a){var b=this._cacheScale;return this._rectangle.setValues(this._cacheOffsetX,this._cacheOffsetY,a.width/b,a.height/b)}return null},b.getTransformedBounds=function(){return this._getBounds()},b.setBounds=function(a,b,c,d){null==a&&(this._bounds=a),this._bounds=(this._bounds||new createjs.Rectangle).setValues(a,b,c,d)},b.clone=function(){return this._cloneProps(new a)},b.toString=function(){return"[DisplayObject (name="+this.name+")]"},b._cloneProps=function(a){return a.alpha=this.alpha,a.mouseEnabled=this.mouseEnabled,a.tickEnabled=this.tickEnabled,a.name=this.name,a.regX=this.regX,a.regY=this.regY,a.rotation=this.rotation,a.scaleX=this.scaleX,a.scaleY=this.scaleY,a.shadow=this.shadow,a.skewX=this.skewX,a.skewY=this.skewY,a.visible=this.visible,a.x=this.x,a.y=this.y,a.compositeOperation=this.compositeOperation,a.snapToPixel=this.snapToPixel,a.filters=null==this.filters?null:this.filters.slice(0),a.mask=this.mask,a.hitArea=this.hitArea,a.cursor=this.cursor,a._bounds=this._bounds,a},b._applyShadow=function(a,b){b=b||Shadow.identity,a.shadowColor=b.color,a.shadowOffsetX=b.offsetX,a.shadowOffsetY=b.offsetY,a.shadowBlur=b.blur},b._tick=function(a){var b=this._listeners;b&&b.tick&&(a.target=null,a.propagationStopped=a.immediatePropagationStopped=!1,this.dispatchEvent(a))},b._testHit=function(b){try{var c=b.getImageData(0,0,1,1).data[3]>1}catch(d){if(!a.suppressCrossDomainErrors)throw"An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images."}return c},b._applyFilters=function(){if(this.filters&&0!=this.filters.length&&this.cacheCanvas)for(var a=this.filters.length,b=this.cacheCanvas.getContext("2d"),c=this.cacheCanvas.width,d=this.cacheCanvas.height,e=0;a>e;e++)this.filters[e].applyFilter(b,0,0,c,d)},b._getFilterBounds=function(){var a,b=this.filters,c=this._rectangle.setValues(0,0,0,0);if(!b||!(a=b.length))return c;for(var d=0;a>d;d++){var e=this.filters[d];e.getBounds&&e.getBounds(c)}return c},b._getBounds=function(a,b){return this._transformBounds(this.getBounds(),a,b)},b._transformBounds=function(a,b,c){if(!a)return a;var d=a.x,e=a.y,f=a.width,g=a.height,h=this._props.matrix;h=c?h.identity():this.getMatrix(h),(d||e)&&h.appendTransform(0,0,1,1,0,0,0,-d,-e),b&&h.prependMatrix(b);var i=f*h.a,j=f*h.b,k=g*h.c,l=g*h.d,m=h.tx,n=h.ty,o=m,p=m,q=n,r=n;return(d=i+m)p&&(p=d),(d=i+k+m)p&&(p=d),(d=k+m)p&&(p=d),(e=j+n)r&&(r=e),(e=j+l+n)r&&(r=e),(e=l+n)r&&(r=e),a.setValues(o,q,p-o,r-q)},b._hasMouseEventListener=function(){for(var b=a._MOUSE_EVENTS,c=0,d=b.length;d>c;c++)if(this.hasEventListener(b[c]))return!0;return!!this.cursor},createjs.DisplayObject=createjs.promote(a,"EventDispatcher")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this.DisplayObject_constructor(),this.children=[],this.mouseChildren=!0,this.tickChildren=!0}var b=createjs.extend(a,createjs.DisplayObject);b.getNumChildren=function(){return this.children.length};try{Object.defineProperties(b,{numChildren:{get:b.getNumChildren}})}catch(c){}b.initialize=a,b.isVisible=function(){var a=this.cacheCanvas||this.children.length;return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;for(var c=this.children.slice(),d=0,e=c.length;e>d;d++){var f=c[d];f.isVisible()&&(a.save(),f.updateContext(a),f.draw(a),a.restore())}return!0},b.addChild=function(a){if(null==a)return a;var b=arguments.length;if(b>1){for(var c=0;b>c;c++)this.addChild(arguments[c]);return arguments[b-1]}return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.push(a),a.dispatchEvent("added"),a},b.addChildAt=function(a,b){var c=arguments.length,d=arguments[c-1];if(0>d||d>this.children.length)return arguments[c-2];if(c>2){for(var e=0;c-1>e;e++)this.addChildAt(arguments[e],d+e);return arguments[c-2]}return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.splice(b,0,a),a.dispatchEvent("added"),a},b.removeChild=function(a){var b=arguments.length;if(b>1){for(var c=!0,d=0;b>d;d++)c=c&&this.removeChild(arguments[d]);return c}return this.removeChildAt(createjs.indexOf(this.children,a))},b.removeChildAt=function(a){var b=arguments.length;if(b>1){for(var c=[],d=0;b>d;d++)c[d]=arguments[d];c.sort(function(a,b){return b-a});for(var e=!0,d=0;b>d;d++)e=e&&this.removeChildAt(c[d]);return e}if(0>a||a>this.children.length-1)return!1;var f=this.children[a];return f&&(f.parent=null),this.children.splice(a,1),f.dispatchEvent("removed"),!0},b.removeAllChildren=function(){for(var a=this.children;a.length;)this.removeChildAt(0)},b.getChildAt=function(a){return this.children[a]},b.getChildByName=function(a){for(var b=this.children,c=0,d=b.length;d>c;c++)if(b[c].name==a)return b[c];return null},b.sortChildren=function(a){this.children.sort(a)},b.getChildIndex=function(a){return createjs.indexOf(this.children,a)},b.swapChildrenAt=function(a,b){var c=this.children,d=c[a],e=c[b];d&&e&&(c[a]=e,c[b]=d)},b.swapChildren=function(a,b){for(var c,d,e=this.children,f=0,g=e.length;g>f&&(e[f]==a&&(c=f),e[f]==b&&(d=f),null==c||null==d);f++);f!=g&&(e[c]=b,e[d]=a)},b.setChildIndex=function(a,b){var c=this.children,d=c.length;if(!(a.parent!=this||0>b||b>=d)){for(var e=0;d>e&&c[e]!=a;e++);e!=d&&e!=b&&(c.splice(e,1),c.splice(b,0,a))}},b.contains=function(a){for(;a;){if(a==this)return!0;a=a.parent}return!1},b.hitTest=function(a,b){return null!=this.getObjectUnderPoint(a,b)},b.getObjectsUnderPoint=function(a,b,c){var d=[],e=this.localToGlobal(a,b);return this._getObjectsUnderPoint(e.x,e.y,d,c>0,1==c),d},b.getObjectUnderPoint=function(a,b,c){var d=this.localToGlobal(a,b);return this._getObjectsUnderPoint(d.x,d.y,null,c>0,1==c)},b.getBounds=function(){return this._getBounds(null,!0)},b.getTransformedBounds=function(){return this._getBounds()},b.clone=function(b){var c=this._cloneProps(new a);return b&&this._cloneChildren(c),c},b.toString=function(){return"[Container (name="+this.name+")]"},b._tick=function(a){if(this.tickChildren)for(var b=this.children.length-1;b>=0;b--){var c=this.children[b];c.tickEnabled&&c._tick&&c._tick(a)}this.DisplayObject__tick(a)},b._cloneChildren=function(a){a.children.length&&a.removeAllChildren();for(var b=a.children,c=0,d=this.children.length;d>c;c++){var e=this.children[c].clone(!0);e.parent=a,b.push(e)}},b._getObjectsUnderPoint=function(b,c,d,e,f,g){if(g=g||0,!g&&!this._testMask(this,b,c))return null;var h,i=createjs.DisplayObject._hitTestContext;f=f||e&&this._hasMouseEventListener();for(var j=this.children,k=j.length,l=k-1;l>=0;l--){var m=j[l],n=m.hitArea;if(m.visible&&(n||m.isVisible())&&(!e||m.mouseEnabled)&&(n||this._testMask(m,b,c)))if(!n&&m instanceof a){var o=m._getObjectsUnderPoint(b,c,d,e,f,g+1);if(!d&&o)return e&&!this.mouseChildren?this:o}else{if(e&&!f&&!m._hasMouseEventListener())continue;var p=m.getConcatenatedDisplayProps(m._props);if(h=p.matrix,n&&(h.appendMatrix(n.getMatrix(n._props.matrix)),p.alpha=n.alpha),i.globalAlpha=p.alpha,i.setTransform(h.a,h.b,h.c,h.d,h.tx-b,h.ty-c),(n||m).draw(i),!this._testHit(i))continue;if(i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,2,2),!d)return e&&!this.mouseChildren?this:m;d.push(m)}}return null},b._testMask=function(a,b,c){var d=a.mask;if(!d||!d.graphics||d.graphics.isEmpty())return!0;var e=this._props.matrix,f=a.parent;e=f?f.getConcatenatedMatrix(e):e.identity(),e=d.getMatrix(d._props.matrix).prependMatrix(e);var g=createjs.DisplayObject._hitTestContext;return g.setTransform(e.a,e.b,e.c,e.d,e.tx-b,e.ty-c),d.graphics.drawAsPath(g),g.fillStyle="#000",g.fill(),this._testHit(g)?(g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,2,2),!0):!1},b._getBounds=function(a,b){var c=this.DisplayObject_getBounds();if(c)return this._transformBounds(c,a,b);var d=this._props.matrix;d=b?d.identity():this.getMatrix(d),a&&d.prependMatrix(a);for(var e=this.children.length,f=null,g=0;e>g;g++){var h=this.children[g];h.visible&&(c=h._getBounds(d))&&(f?f.extend(c.x,c.y,c.width,c.height):f=c.clone())}return f},createjs.Container=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.Container_constructor(),this.autoClear=!0,this.canvas="string"==typeof a?document.getElementById(a):a,this.mouseX=0,this.mouseY=0,this.drawRect=null,this.snapToPixelEnabled=!1,this.mouseInBounds=!1,this.tickOnUpdate=!0,this.mouseMoveOutside=!1,this.preventSelection=!0,this._pointerData={},this._pointerCount=0,this._primaryPointerID=null,this._mouseOverIntervalID=null,this._nextStage=null,this._prevStage=null,this.enableDOMEvents(!0)}var b=createjs.extend(a,createjs.Container);b._get_nextStage=function(){return this._nextStage},b._set_nextStage=function(a){this._nextStage&&(this._nextStage._prevStage=null),a&&(a._prevStage=this),this._nextStage=a};try{Object.defineProperties(b,{nextStage:{get:b._get_nextStage,set:b._set_nextStage}})}catch(c){}b.update=function(a){if(this.canvas&&(this.tickOnUpdate&&this.tick(a),this.dispatchEvent("drawstart",!1,!0)!==!1)){createjs.DisplayObject._snapToPixelEnabled=this.snapToPixelEnabled;var b=this.drawRect,c=this.canvas.getContext("2d");c.setTransform(1,0,0,1,0,0),this.autoClear&&(b?c.clearRect(b.x,b.y,b.width,b.height):c.clearRect(0,0,this.canvas.width+1,this.canvas.height+1)),c.save(),this.drawRect&&(c.beginPath(),c.rect(b.x,b.y,b.width,b.height),c.clip()),this.updateContext(c),this.draw(c,!1),c.restore(),this.dispatchEvent("drawend")}},b.tick=function(a){if(this.tickEnabled&&this.dispatchEvent("tickstart",!1,!0)!==!1){var b=new createjs.Event("tick");if(a)for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);this._tick(b),this.dispatchEvent("tickend")}},b.handleEvent=function(a){"tick"==a.type&&this.update(a)},b.clear=function(){if(this.canvas){var a=this.canvas.getContext("2d");a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,this.canvas.width+1,this.canvas.height+1)}},b.toDataURL=function(a,b){var c,d=this.canvas.getContext("2d"),e=this.canvas.width,f=this.canvas.height;if(a){c=d.getImageData(0,0,e,f);var g=d.globalCompositeOperation;d.globalCompositeOperation="destination-over",d.fillStyle=a,d.fillRect(0,0,e,f)}var h=this.canvas.toDataURL(b||"image/png");return a&&(d.putImageData(c,0,0),d.globalCompositeOperation=g),h},b.enableMouseOver=function(a){if(this._mouseOverIntervalID&&(clearInterval(this._mouseOverIntervalID),this._mouseOverIntervalID=null,0==a&&this._testMouseOver(!0)),null==a)a=20;else if(0>=a)return;var b=this;this._mouseOverIntervalID=setInterval(function(){b._testMouseOver()},1e3/Math.min(50,a))},b.enableDOMEvents=function(a){null==a&&(a=!0);var b,c,d=this._eventListeners;if(!a&&d){for(b in d)c=d[b],c.t.removeEventListener(b,c.f,!1);this._eventListeners=null}else if(a&&!d&&this.canvas){var e=window.addEventListener?window:document,f=this;d=this._eventListeners={},d.mouseup={t:e,f:function(a){f._handleMouseUp(a)}},d.mousemove={t:e,f:function(a){f._handleMouseMove(a)}},d.dblclick={t:this.canvas,f:function(a){f._handleDoubleClick(a)}},d.mousedown={t:this.canvas,f:function(a){f._handleMouseDown(a)}};for(b in d)c=d[b],c.t.addEventListener(b,c.f,!1)}},b.clone=function(){throw"Stage cannot be cloned."},b.toString=function(){return"[Stage (name="+this.name+")]"},b._getElementRect=function(a){var b;try{b=a.getBoundingClientRect()}catch(c){b={top:a.offsetTop,left:a.offsetLeft,width:a.offsetWidth,height:a.offsetHeight}}var d=(window.pageXOffset||document.scrollLeft||0)-(document.clientLeft||document.body.clientLeft||0),e=(window.pageYOffset||document.scrollTop||0)-(document.clientTop||document.body.clientTop||0),f=window.getComputedStyle?getComputedStyle(a,null):a.currentStyle,g=parseInt(f.paddingLeft)+parseInt(f.borderLeftWidth),h=parseInt(f.paddingTop)+parseInt(f.borderTopWidth),i=parseInt(f.paddingRight)+parseInt(f.borderRightWidth),j=parseInt(f.paddingBottom)+parseInt(f.borderBottomWidth);return{left:b.left+d+g,right:b.right+d-i,top:b.top+e+h,bottom:b.bottom+e-j}},b._getPointerData=function(a){var b=this._pointerData[a];return b||(b=this._pointerData[a]={x:0,y:0}),b},b._handleMouseMove=function(a){a||(a=window.event),this._handlePointerMove(-1,a,a.pageX,a.pageY)},b._handlePointerMove=function(a,b,c,d,e){if((!this._prevStage||void 0!==e)&&this.canvas){var f=this._nextStage,g=this._getPointerData(a),h=g.inBounds;this._updatePointerPosition(a,b,c,d),(h||g.inBounds||this.mouseMoveOutside)&&(-1===a&&g.inBounds==!h&&this._dispatchMouseEvent(this,h?"mouseleave":"mouseenter",!1,a,g,b),this._dispatchMouseEvent(this,"stagemousemove",!1,a,g,b),this._dispatchMouseEvent(g.target,"pressmove",!0,a,g,b)),f&&f._handlePointerMove(a,b,c,d,null)}},b._updatePointerPosition=function(a,b,c,d){var e=this._getElementRect(this.canvas);c-=e.left,d-=e.top;var f=this.canvas.width,g=this.canvas.height;c/=(e.right-e.left)/f,d/=(e.bottom-e.top)/g;var h=this._getPointerData(a);(h.inBounds=c>=0&&d>=0&&f-1>=c&&g-1>=d)?(h.x=c,h.y=d):this.mouseMoveOutside&&(h.x=0>c?0:c>f-1?f-1:c,h.y=0>d?0:d>g-1?g-1:d),h.posEvtObj=b,h.rawX=c,h.rawY=d,(a===this._primaryPointerID||-1===a)&&(this.mouseX=h.x,this.mouseY=h.y,this.mouseInBounds=h.inBounds)},b._handleMouseUp=function(a){this._handlePointerUp(-1,a,!1)},b._handlePointerUp=function(a,b,c,d){var e=this._nextStage,f=this._getPointerData(a);if(!this._prevStage||void 0!==d){var g=null,h=f.target;d||!h&&!e||(g=this._getObjectsUnderPoint(f.x,f.y,null,!0)),f.down&&(this._dispatchMouseEvent(this,"stagemouseup",!1,a,f,b,g),f.down=!1),g==h&&this._dispatchMouseEvent(h,"click",!0,a,f,b),this._dispatchMouseEvent(h,"pressup",!0,a,f,b),c?(a==this._primaryPointerID&&(this._primaryPointerID=null),delete this._pointerData[a]):f.target=null,e&&e._handlePointerUp(a,b,c,d||g&&this)}},b._handleMouseDown=function(a){this._handlePointerDown(-1,a,a.pageX,a.pageY)},b._handlePointerDown=function(a,b,c,d,e){this.preventSelection&&b.preventDefault(),(null==this._primaryPointerID||-1===a)&&(this._primaryPointerID=a),null!=d&&this._updatePointerPosition(a,b,c,d);var f=null,g=this._nextStage,h=this._getPointerData(a);e||(f=h.target=this._getObjectsUnderPoint(h.x,h.y,null,!0)),h.inBounds&&(this._dispatchMouseEvent(this,"stagemousedown",!1,a,h,b,f),h.down=!0),this._dispatchMouseEvent(f,"mousedown",!0,a,h,b),g&&g._handlePointerDown(a,b,c,d,e||f&&this)},b._testMouseOver=function(a,b,c){if(!this._prevStage||void 0!==b){var d=this._nextStage;if(!this._mouseOverIntervalID)return void(d&&d._testMouseOver(a,b,c));var e=this._getPointerData(-1);if(e&&(a||this.mouseX!=this._mouseOverX||this.mouseY!=this._mouseOverY||!this.mouseInBounds)){var f,g,h,i=e.posEvtObj,j=c||i&&i.target==this.canvas,k=null,l=-1,m="";!b&&(a||this.mouseInBounds&&j)&&(k=this._getObjectsUnderPoint(this.mouseX,this.mouseY,null,!0),this._mouseOverX=this.mouseX,this._mouseOverY=this.mouseY);var n=this._mouseOverTarget||[],o=n[n.length-1],p=this._mouseOverTarget=[];for(f=k;f;)p.unshift(f),m||(m=f.cursor),f=f.parent;for(this.canvas.style.cursor=m,!b&&c&&(c.canvas.style.cursor=m),g=0,h=p.length;h>g&&p[g]==n[g];g++)l=g;for(o!=k&&this._dispatchMouseEvent(o,"mouseout",!0,-1,e,i,k),g=n.length-1;g>l;g--)this._dispatchMouseEvent(n[g],"rollout",!1,-1,e,i,k);for(g=p.length-1;g>l;g--)this._dispatchMouseEvent(p[g],"rollover",!1,-1,e,i,o);o!=k&&this._dispatchMouseEvent(k,"mouseover",!0,-1,e,i,o),d&&d._testMouseOver(a,b||k&&this,c||j&&this)}}},b._handleDoubleClick=function(a,b){var c=null,d=this._nextStage,e=this._getPointerData(-1);b||(c=this._getObjectsUnderPoint(e.x,e.y,null,!0),this._dispatchMouseEvent(c,"dblclick",!0,-1,e,a)),d&&d._handleDoubleClick(a,b||c&&this)},b._dispatchMouseEvent=function(a,b,c,d,e,f,g){if(a&&(c||a.hasEventListener(b))){var h=new createjs.MouseEvent(b,c,!1,e.x,e.y,f,d,d===this._primaryPointerID||-1===d,e.rawX,e.rawY,g);a.dispatchEvent(h)}},createjs.Stage=createjs.promote(a,"Container")}(),this.createjs=this.createjs||{},function(){function a(a){this.DisplayObject_constructor(),"string"==typeof a?(this.image=document.createElement("img"),this.image.src=a):this.image=a,this.sourceRect=null}var b=createjs.extend(a,createjs.DisplayObject);b.initialize=a,b.isVisible=function(){var a=this.image,b=this.cacheCanvas||a&&(a.naturalWidth||a.getContext||a.readyState>=2);return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&b)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b)||!this.image)return!0;var c=this.image,d=this.sourceRect;if(d){var e=d.x,f=d.y,g=e+d.width,h=f+d.height,i=0,j=0,k=c.width,l=c.height;0>e&&(i-=e,e=0),g>k&&(g=k),0>f&&(j-=f,f=0),h>l&&(h=l),a.drawImage(c,e,f,g-e,h-f,i,j,g-e,h-f)}else a.drawImage(c,0,0);return!0},b.getBounds=function(){var a=this.DisplayObject_getBounds();if(a)return a;var b=this.image,c=this.sourceRect||b,d=b&&(b.naturalWidth||b.getContext||b.readyState>=2);return d?this._rectangle.setValues(0,0,c.width,c.height):null},b.clone=function(){var b=new a(this.image);return this.sourceRect&&(b.sourceRect=this.sourceRect.clone()),this._cloneProps(b),b},b.toString=function(){return"[Bitmap (name="+this.name+")]"},createjs.Bitmap=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.DisplayObject_constructor(),this.currentFrame=0,this.currentAnimation=null,this.paused=!0,this.spriteSheet=a,this.currentAnimationFrame=0,this.framerate=0,this._animation=null,this._currentFrame=null,this._skipAdvance=!1,null!=b&&this.gotoAndPlay(b)}var b=createjs.extend(a,createjs.DisplayObject);b.initialize=a,b.isVisible=function(){var a=this.cacheCanvas||this.spriteSheet.complete;return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;this._normalizeFrame();var c=this.spriteSheet.getFrame(0|this._currentFrame);if(!c)return!1;var d=c.rect;return d.width&&d.height&&a.drawImage(c.image,d.x,d.y,d.width,d.height,-c.regX,-c.regY,d.width,d.height),!0},b.play=function(){this.paused=!1},b.stop=function(){this.paused=!0},b.gotoAndPlay=function(a){this.paused=!1,this._skipAdvance=!0,this._goto(a)},b.gotoAndStop=function(a){this.paused=!0,this._goto(a)},b.advance=function(a){var b=this.framerate||this.spriteSheet.framerate,c=b&&null!=a?a/(1e3/b):1;this._normalizeFrame(c)},b.getBounds=function(){return this.DisplayObject_getBounds()||this.spriteSheet.getFrameBounds(this.currentFrame,this._rectangle)},b.clone=function(){return this._cloneProps(new a(this.spriteSheet))},b.toString=function(){return"[Sprite (name="+this.name+")]"},b._cloneProps=function(a){return this.DisplayObject__cloneProps(a),a.currentFrame=this.currentFrame,a.currentAnimation=this.currentAnimation,a.paused=this.paused,a.currentAnimationFrame=this.currentAnimationFrame,a.framerate=this.framerate,a._animation=this._animation,a._currentFrame=this._currentFrame,a._skipAdvance=this._skipAdvance,a},b._tick=function(a){this.paused||(this._skipAdvance||this.advance(a&&a.delta),this._skipAdvance=!1),this.DisplayObject__tick(a)},b._normalizeFrame=function(a){a=a||0;var b,c=this._animation,d=this.paused,e=this._currentFrame;if(c){var f=c.speed||1,g=this.currentAnimationFrame;if(b=c.frames.length,g+a*f>=b){var h=c.next;if(this._dispatchAnimationEnd(c,e,d,h,b-1))return;if(h)return this._goto(h,a-(b-g)/f);this.paused=!0,g=c.frames.length-1}else g+=a*f;this.currentAnimationFrame=g,this._currentFrame=c.frames[0|g]}else if(e=this._currentFrame+=a,b=this.spriteSheet.getNumFrames(),e>=b&&b>0&&!this._dispatchAnimationEnd(c,e,d,b-1)&&(this._currentFrame-=b)>=b)return this._normalizeFrame();e=0|this._currentFrame,this.currentFrame!=e&&(this.currentFrame=e,this.dispatchEvent("change"))},b._dispatchAnimationEnd=function(a,b,c,d,e){var f=a?a.name:null;if(this.hasEventListener("animationend")){var g=new createjs.Event("animationend");g.name=f,g.next=d,this.dispatchEvent(g)}var h=this._animation!=a||this._currentFrame!=b;return h||c||!this.paused||(this.currentAnimationFrame=e,h=!0),h},b._goto=function(a,b){if(this.currentAnimationFrame=0,isNaN(a)){var c=this.spriteSheet.getAnimation(a);c&&(this._animation=c,this.currentAnimation=a,this._normalizeFrame(b))}else this.currentAnimation=this._animation=null,this._currentFrame=a,this._normalizeFrame()},createjs.Sprite=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.DisplayObject_constructor(),this.graphics=a?a:new createjs.Graphics}var b=createjs.extend(a,createjs.DisplayObject);b.isVisible=function(){var a=this.cacheCanvas||this.graphics&&!this.graphics.isEmpty();return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){return this.DisplayObject_draw(a,b)?!0:(this.graphics.draw(a,this),!0)},b.clone=function(b){var c=b&&this.graphics?this.graphics.clone():this.graphics;return this._cloneProps(new a(c))},b.toString=function(){return"[Shape (name="+this.name+")]"},createjs.Shape=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c){this.DisplayObject_constructor(),this.text=a,this.font=b,this.color=c,this.textAlign="left",this.textBaseline="top",this.maxWidth=null,this.outline=0,this.lineHeight=0,this.lineWidth=null}var b=createjs.extend(a,createjs.DisplayObject),c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");c.getContext&&(a._workingContext=c.getContext("2d"),c.width=c.height=1),a.H_OFFSETS={start:0,left:0,center:-.5,end:-1,right:-1},a.V_OFFSETS={top:0,hanging:-.01,middle:-.4,alphabetic:-.8,ideographic:-.85,bottom:-1},b.isVisible=function(){var a=this.cacheCanvas||null!=this.text&&""!==this.text;return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;var c=this.color||"#000";return this.outline?(a.strokeStyle=c,a.lineWidth=1*this.outline):a.fillStyle=c,this._drawText(this._prepContext(a)),!0},b.getMeasuredWidth=function(){return this._getMeasuredWidth(this.text)},b.getMeasuredLineHeight=function(){return 1.2*this._getMeasuredWidth("M")},b.getMeasuredHeight=function(){return this._drawText(null,{}).height},b.getBounds=function(){var b=this.DisplayObject_getBounds();if(b)return b;if(null==this.text||""===this.text)return null;var c=this._drawText(null,{}),d=this.maxWidth&&this.maxWidthj;j++){var l=i[j],m=null;if(null!=this.lineWidth&&(m=b.measureText(l).width)>this.lineWidth){var n=l.split(/(\s)/);l=n[0],m=b.measureText(l).width;for(var o=1,p=n.length;p>o;o+=2){var q=b.measureText(n[o]+n[o+1]).width;m+q>this.lineWidth?(e&&this._drawTextLine(b,l,h*f),d&&d.push(l),m>g&&(g=m),l=n[o+1],m=b.measureText(l).width,h++):(l+=n[o]+n[o+1],m+=q)}}e&&this._drawTextLine(b,l,h*f),d&&d.push(l),c&&null==m&&(m=b.measureText(l).width),m>g&&(g=m),h++}return c&&(c.width=g,c.height=h*f),e||b.restore(),c},b._drawTextLine=function(a,b,c){this.outline?a.strokeText(b,0,c,this.maxWidth||65535):a.fillText(b,0,c,this.maxWidth||65535)},b._getMeasuredWidth=function(b){var c=a._workingContext;c.save();var d=this._prepContext(c).measureText(b).width;return c.restore(),d},createjs.Text=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.Container_constructor(),this.text=a||"",this.spriteSheet=b,this.lineHeight=0,this.letterSpacing=0,this.spaceWidth=0,this._oldProps={text:0,spriteSheet:0,lineHeight:0,letterSpacing:0,spaceWidth:0}}var b=createjs.extend(a,createjs.Container);a.maxPoolSize=100,a._spritePool=[],b.draw=function(a,b){this.DisplayObject_draw(a,b)||(this._updateText(),this.Container_draw(a,b))},b.getBounds=function(){return this._updateText(),this.Container_getBounds()},b.isVisible=function(){var a=this.cacheCanvas||this.spriteSheet&&this.spriteSheet.complete&&this.text;return!!(this.visible&&this.alpha>0&&0!==this.scaleX&&0!==this.scaleY&&a)},b.clone=function(){return this._cloneProps(new a(this.text,this.spriteSheet))},b.addChild=b.addChildAt=b.removeChild=b.removeChildAt=b.removeAllChildren=function(){},b._cloneProps=function(a){return this.Container__cloneProps(a),a.lineHeight=this.lineHeight,a.letterSpacing=this.letterSpacing,a.spaceWidth=this.spaceWidth,a},b._getFrameIndex=function(a,b){var c,d=b.getAnimation(a);return d||(a!=(c=a.toUpperCase())||a!=(c=a.toLowerCase())||(c=null),c&&(d=b.getAnimation(c))),d&&d.frames[0]},b._getFrame=function(a,b){var c=this._getFrameIndex(a,b);return null==c?c:b.getFrame(c)},b._getLineHeight=function(a){var b=this._getFrame("1",a)||this._getFrame("T",a)||this._getFrame("L",a)||a.getFrame(0);return b?b.rect.height:1},b._getSpaceWidth=function(a){var b=this._getFrame("1",a)||this._getFrame("l",a)||this._getFrame("e",a)||this._getFrame("a",a)||a.getFrame(0);return b?b.rect.width:1},b._updateText=function(){var b,c=0,d=0,e=this._oldProps,f=!1,g=this.spaceWidth,h=this.lineHeight,i=this.spriteSheet,j=a._spritePool,k=this.children,l=0,m=k.length;for(var n in e)e[n]!=this[n]&&(e[n]=this[n],f=!0);if(f){var o=!!this._getFrame(" ",i);o||g||(g=this._getSpaceWidth(i)),h||(h=this._getLineHeight(i));for(var p=0,q=this.text.length;q>p;p++){var r=this.text.charAt(p);if(" "!=r||o)if("\n"!=r&&"\r"!=r){var s=this._getFrameIndex(r,i);null!=s&&(m>l?b=k[l]:(k.push(b=j.length?j.pop():new createjs.Sprite),b.parent=this,m++),b.spriteSheet=i,b.gotoAndStop(s),b.x=c,b.y=d,l++,c+=b.getBounds().width+this.letterSpacing)}else"\r"==r&&"\n"==this.text.charAt(p+1)&&p++,c=0,d+=h;else c+=g}for(;m>l;)j.push(b=k.pop()),b.parent=null,m--;j.length>a.maxPoolSize&&(j.length=a.maxPoolSize)}},createjs.BitmapText=createjs.promote(a,"Container")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"SpriteSheetUtils cannot be instantiated"}var b=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");b.getContext&&(a._workingCanvas=b,a._workingContext=b.getContext("2d"),b.width=b.height=1),a.addFlippedFrames=function(b,c,d,e){if(c||d||e){var f=0;c&&a._flip(b,++f,!0,!1),d&&a._flip(b,++f,!1,!0),e&&a._flip(b,++f,!0,!0)}},a.extractFrame=function(b,c){isNaN(c)&&(c=b.getAnimation(c).frames[0]);var d=b.getFrame(c);if(!d)return null;var e=d.rect,f=a._workingCanvas;f.width=e.width,f.height=e.height,a._workingContext.drawImage(d.image,e.x,e.y,e.width,e.height,0,0,e.width,e.height);var g=document.createElement("img");return g.src=f.toDataURL("image/png"),g},a.mergeAlpha=function(a,b,c){c||(c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")),c.width=Math.max(b.width,a.width),c.height=Math.max(b.height,a.height);var d=c.getContext("2d");return d.save(),d.drawImage(a,0,0),d.globalCompositeOperation="destination-in",d.drawImage(b,0,0),d.restore(),c},a._flip=function(b,c,d,e){for(var f=b._images,g=a._workingCanvas,h=a._workingContext,i=f.length/c,j=0;i>j;j++){var k=f[j];k.__tmp=j,h.setTransform(1,0,0,1,0,0),h.clearRect(0,0,g.width+1,g.height+1),g.width=k.width,g.height=k.height,h.setTransform(d?-1:1,0,0,e?-1:1,d?k.width:0,e?k.height:0),h.drawImage(k,0,0); -var l=document.createElement("img");l.src=g.toDataURL("image/png"),l.width=k.width,l.height=k.height,f.push(l)}var m=b._frames,n=m.length/c;for(j=0;n>j;j++){k=m[j];var o=k.rect.clone();l=f[k.image.__tmp+i*c];var p={image:l,rect:o,regX:k.regX,regY:k.regY};d&&(o.x=l.width-o.x-o.width,p.regX=o.width-k.regX),e&&(o.y=l.height-o.y-o.height,p.regY=o.height-k.regY),m.push(p)}var q="_"+(d?"h":"")+(e?"v":""),r=b._animations,s=b._data,t=r.length/c;for(j=0;t>j;j++){var u=r[j];k=s[u];var v={name:u+q,speed:k.speed,next:k.next,frames:[]};k.next&&(v.next+=q),m=k.frames;for(var w=0,x=m.length;x>w;w++)v.frames.push(m[w]+n*c);s[v.name]=v,r.push(v.name)}},createjs.SpriteSheetUtils=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this.EventDispatcher_constructor(),this.maxWidth=2048,this.maxHeight=2048,this.spriteSheet=null,this.scale=1,this.padding=1,this.timeSlice=.3,this.progress=-1,this._frames=[],this._animations={},this._data=null,this._nextFrameIndex=0,this._index=0,this._timerID=null,this._scale=1}var b=createjs.extend(a,createjs.EventDispatcher);a.ERR_DIMENSIONS="frame dimensions exceed max spritesheet dimensions",a.ERR_RUNNING="a build is already running",b.addFrame=function(b,c,d,e,f){if(this._data)throw a.ERR_RUNNING;var g=c||b.bounds||b.nominalBounds;return!g&&b.getBounds&&(g=b.getBounds()),g?(d=d||1,this._frames.push({source:b,sourceRect:g,scale:d,funct:e,data:f,index:this._frames.length,height:g.height*d})-1):null},b.addAnimation=function(b,c,d,e){if(this._data)throw a.ERR_RUNNING;this._animations[b]={frames:c,next:d,frequency:e}},b.addMovieClip=function(b,c,d,e,f,g){if(this._data)throw a.ERR_RUNNING;var h=b.frameBounds,i=c||b.bounds||b.nominalBounds;if(!i&&b.getBounds&&(i=b.getBounds()),i||h){var j,k,l=this._frames.length,m=b.timeline.duration;for(j=0;m>j;j++){var n=h&&h[j]?h[j]:i;this.addFrame(b,n,d,this._setupMovieClipFrame,{i:j,f:e,d:f})}var o=b.timeline._labels,p=[];for(var q in o)p.push({index:o[q],label:q});if(p.length)for(p.sort(function(a,b){return a.index-b.index}),j=0,k=p.length;k>j;j++){for(var r=p[j].label,s=l+p[j].index,t=l+(j==k-1?m:p[j+1].index),u=[],v=s;t>v;v++)u.push(v);(!g||(r=g(r,b,s,t)))&&this.addAnimation(r,u,!0)}}},b.build=function(){if(this._data)throw a.ERR_RUNNING;for(this._startBuild();this._drawNext(););return this._endBuild(),this.spriteSheet},b.buildAsync=function(b){if(this._data)throw a.ERR_RUNNING;this.timeSlice=b,this._startBuild();var c=this;this._timerID=setTimeout(function(){c._run()},50-50*Math.max(.01,Math.min(.99,this.timeSlice||.3)))},b.stopAsync=function(){clearTimeout(this._timerID),this._data=null},b.clone=function(){throw"SpriteSheetBuilder cannot be cloned."},b.toString=function(){return"[SpriteSheetBuilder]"},b._startBuild=function(){var b=this.padding||0;this.progress=0,this.spriteSheet=null,this._index=0,this._scale=this.scale;var c=[];this._data={images:[],frames:c,animations:this._animations};var d=this._frames.slice();if(d.sort(function(a,b){return a.height<=b.height?-1:1}),d[d.length-1].height+2*b>this.maxHeight)throw a.ERR_DIMENSIONS;for(var e=0,f=0,g=0;d.length;){var h=this._fillRow(d,e,g,c,b);if(h.w>f&&(f=h.w),e+=h.h,!h.h||!d.length){var i=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");i.width=this._getSize(f,this.maxWidth),i.height=this._getSize(e,this.maxHeight),this._data.images[g]=i,h.h||(f=e=0,g++)}}},b._setupMovieClipFrame=function(a,b){var c=a.actionsEnabled;a.actionsEnabled=!1,a.gotoAndStop(b.i),a.actionsEnabled=c,b.f&&b.f(a,b.d,b.i)},b._getSize=function(a,b){for(var c=4;Math.pow(2,++c)=0;l--){var m=b[l],n=this._scale*m.scale,o=m.sourceRect,p=m.source,q=Math.floor(n*o.x-f),r=Math.floor(n*o.y-f),s=Math.ceil(n*o.height+2*f),t=Math.ceil(n*o.width+2*f);if(t>g)throw a.ERR_DIMENSIONS;s>i||j+t>g||(m.img=d,m.rect=new createjs.Rectangle(j,c,t,s),k=k||s,b.splice(l,1),e[m.index]=[j,c,t,s,d,Math.round(-q+n*p.regX-f),Math.round(-r+n*p.regY-f)],j+=t)}return{w:j,h:k}},b._endBuild=function(){this.spriteSheet=new createjs.SpriteSheet(this._data),this._data=null,this.progress=1,this.dispatchEvent("complete")},b._run=function(){for(var a=50*Math.max(.01,Math.min(.99,this.timeSlice||.3)),b=(new Date).getTime()+a,c=!1;b>(new Date).getTime();)if(!this._drawNext()){c=!0;break}if(c)this._endBuild();else{var d=this;this._timerID=setTimeout(function(){d._run()},50-a)}var e=this.progress=this._index/this._frames.length;if(this.hasEventListener("progress")){var f=new createjs.Event("progress");f.progress=e,this.dispatchEvent(f)}},b._drawNext=function(){var a=this._frames[this._index],b=a.scale*this._scale,c=a.rect,d=a.sourceRect,e=this._data.images[a.img],f=e.getContext("2d");return a.funct&&a.funct(a.source,a.data),f.save(),f.beginPath(),f.rect(c.x,c.y,c.width,c.height),f.clip(),f.translate(Math.ceil(c.x-d.x*b),Math.ceil(c.y-d.y*b)),f.scale(b,b),a.source.draw(f),f.restore(),++this._indexa)&&(a=0),(isNaN(b)||0>b)&&(b=0),(isNaN(c)||1>c)&&(c=1),this.blurX=0|a,this.blurY=0|b,this.quality=0|c}var b=createjs.extend(a,createjs.Filter);a.MUL_TABLE=[1,171,205,293,57,373,79,137,241,27,391,357,41,19,283,265,497,469,443,421,25,191,365,349,335,161,155,149,9,278,269,261,505,245,475,231,449,437,213,415,405,395,193,377,369,361,353,345,169,331,325,319,313,307,301,37,145,285,281,69,271,267,263,259,509,501,493,243,479,118,465,459,113,446,55,435,429,423,209,413,51,403,199,393,97,3,379,375,371,367,363,359,355,351,347,43,85,337,333,165,327,323,5,317,157,311,77,305,303,75,297,294,73,289,287,71,141,279,277,275,68,135,67,133,33,262,260,129,511,507,503,499,495,491,61,121,481,477,237,235,467,232,115,457,227,451,7,445,221,439,218,433,215,427,425,211,419,417,207,411,409,203,202,401,399,396,197,49,389,387,385,383,95,189,47,187,93,185,23,183,91,181,45,179,89,177,11,175,87,173,345,343,341,339,337,21,167,83,331,329,327,163,81,323,321,319,159,79,315,313,39,155,309,307,153,305,303,151,75,299,149,37,295,147,73,291,145,289,287,143,285,71,141,281,35,279,139,69,275,137,273,17,271,135,269,267,133,265,33,263,131,261,130,259,129,257,1],a.SHG_TABLE=[0,9,10,11,9,12,10,11,12,9,13,13,10,9,13,13,14,14,14,14,10,13,14,14,14,13,13,13,9,14,14,14,15,14,15,14,15,15,14,15,15,15,14,15,15,15,15,15,14,15,15,15,15,15,15,12,14,15,15,13,15,15,15,15,16,16,16,15,16,14,16,16,14,16,13,16,16,16,15,16,13,16,15,16,14,9,16,16,16,16,16,16,16,16,16,13,14,16,16,15,16,16,10,16,15,16,14,16,16,14,16,16,14,16,16,14,15,16,16,16,14,15,14,15,13,16,16,15,17,17,17,17,17,17,14,15,17,17,16,16,17,16,15,17,16,17,11,17,16,17,16,17,16,17,17,16,17,17,16,17,17,16,16,17,17,17,16,14,17,17,17,17,15,16,14,16,15,16,13,16,15,16,14,16,15,16,12,16,15,16,17,17,17,17,17,13,16,15,17,17,17,16,15,17,17,17,16,15,17,17,14,16,17,17,16,17,17,16,15,17,16,14,17,16,15,17,16,17,17,16,17,15,16,17,14,17,16,15,17,16,17,13,17,16,17,17,16,17,14,17,16,17,16,17,16,17,9],b.getBounds=function(a){var b=0|this.blurX,c=0|this.blurY;if(0>=b&&0>=c)return a;var d=Math.pow(this.quality,.2);return(a||new createjs.Rectangle).pad(b*d+1,c*d+1,b*d+1,c*d+1)},b.clone=function(){return new a(this.blurX,this.blurY,this.quality)},b.toString=function(){return"[BlurFilter]"},b._applyFilter=function(b){var c=this.blurX>>1;if(isNaN(c)||0>c)return!1;var d=this.blurY>>1;if(isNaN(d)||0>d)return!1;if(0==c&&0==d)return!1;var e=this.quality;(isNaN(e)||1>e)&&(e=1),e|=0,e>3&&(e=3),1>e&&(e=1);var f=b.data,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=c+c+1|0,w=d+d+1|0,x=0|b.width,y=0|b.height,z=x-1|0,A=y-1|0,B=c+1|0,C=d+1|0,D={r:0,b:0,g:0,a:0},E=D;for(i=1;v>i;i++)E=E.n={r:0,b:0,g:0,a:0};E.n=D;var F={r:0,b:0,g:0,a:0},G=F;for(i=1;w>i;i++)G=G.n={r:0,b:0,g:0,a:0};G.n=F;for(var H=null,I=0|a.MUL_TABLE[c],J=0|a.SHG_TABLE[c],K=0|a.MUL_TABLE[d],L=0|a.SHG_TABLE[d];e-->0;){m=l=0;var M=I,N=J;for(h=y;--h>-1;){for(n=B*(r=f[0|l]),o=B*(s=f[l+1|0]),p=B*(t=f[l+2|0]),q=B*(u=f[l+3|0]),E=D,i=B;--i>-1;)E.r=r,E.g=s,E.b=t,E.a=u,E=E.n;for(i=1;B>i;i++)j=l+((i>z?z:i)<<2)|0,n+=E.r=f[j],o+=E.g=f[j+1],p+=E.b=f[j+2],q+=E.a=f[j+3],E=E.n;for(H=D,g=0;x>g;g++)f[l++]=n*M>>>N,f[l++]=o*M>>>N,f[l++]=p*M>>>N,f[l++]=q*M>>>N,j=m+((j=g+c+1)g;g++){for(l=g<<2|0,n=C*(r=f[l])|0,o=C*(s=f[l+1|0])|0,p=C*(t=f[l+2|0])|0,q=C*(u=f[l+3|0])|0,G=F,i=0;C>i;i++)G.r=r,G.g=s,G.b=t,G.a=u,G=G.n;for(k=x,i=1;d>=i;i++)l=k+g<<2,n+=G.r=f[l],o+=G.g=f[l+1],p+=G.b=f[l+2],q+=G.a=f[l+3],G=G.n,A>i&&(k+=x);if(l=g,H=F,e>0)for(h=0;y>h;h++)j=l<<2,f[j+3]=u=q*M>>>N,u>0?(f[j]=n*M>>>N,f[j+1]=o*M>>>N,f[j+2]=p*M>>>N):f[j]=f[j+1]=f[j+2]=0,j=g+((j=h+C)h;h++)j=l<<2,f[j+3]=u=q*M>>>N,u>0?(u=255/u,f[j]=(n*M>>>N)*u,f[j+1]=(o*M>>>N)*u,f[j+2]=(p*M>>>N)*u):f[j]=f[j+1]=f[j+2]=0,j=g+((j=h+C)d;d+=4)b[d+3]=c[d]||0;return!0},b._prepAlphaMap=function(){if(!this.alphaMap)return!1;if(this.alphaMap==this._alphaMap&&this._mapData)return!0;this._mapData=null;var a,b=this._alphaMap=this.alphaMap,c=b;b instanceof HTMLCanvasElement?a=c.getContext("2d"):(c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas"),c.width=b.width,c.height=b.height,a=c.getContext("2d"),a.drawImage(b,0,0));try{var d=a.getImageData(0,0,b.width,b.height)}catch(e){return!1}return this._mapData=d.data,!0},createjs.AlphaMapFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.mask=a}var b=createjs.extend(a,createjs.Filter);b.applyFilter=function(a,b,c,d,e,f,g,h){return this.mask?(f=f||a,null==g&&(g=b),null==h&&(h=c),f.save(),a!=f?!1:(f.globalCompositeOperation="destination-in",f.drawImage(this.mask,g,h),f.restore(),!0)):!0},b.clone=function(){return new a(this.mask)},b.toString=function(){return"[AlphaMaskFilter]"},createjs.AlphaMaskFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f,g,h){this.redMultiplier=null!=a?a:1,this.greenMultiplier=null!=b?b:1,this.blueMultiplier=null!=c?c:1,this.alphaMultiplier=null!=d?d:1,this.redOffset=e||0,this.greenOffset=f||0,this.blueOffset=g||0,this.alphaOffset=h||0}var b=createjs.extend(a,createjs.Filter);b.toString=function(){return"[ColorFilter]"},b.clone=function(){return new a(this.redMultiplier,this.greenMultiplier,this.blueMultiplier,this.alphaMultiplier,this.redOffset,this.greenOffset,this.blueOffset,this.alphaOffset)},b._applyFilter=function(a){for(var b=a.data,c=b.length,d=0;c>d;d+=4)b[d]=b[d]*this.redMultiplier+this.redOffset,b[d+1]=b[d+1]*this.greenMultiplier+this.greenOffset,b[d+2]=b[d+2]*this.blueMultiplier+this.blueOffset,b[d+3]=b[d+3]*this.alphaMultiplier+this.alphaOffset;return!0},createjs.ColorFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d){this.setColor(a,b,c,d)}var b=a.prototype;a.DELTA_INDEX=[0,.01,.02,.04,.05,.06,.07,.08,.1,.11,.12,.14,.15,.16,.17,.18,.2,.21,.22,.24,.25,.27,.28,.3,.32,.34,.36,.38,.4,.42,.44,.46,.48,.5,.53,.56,.59,.62,.65,.68,.71,.74,.77,.8,.83,.86,.89,.92,.95,.98,1,1.06,1.12,1.18,1.24,1.3,1.36,1.42,1.48,1.54,1.6,1.66,1.72,1.78,1.84,1.9,1.96,2,2.12,2.25,2.37,2.5,2.62,2.75,2.87,3,3.2,3.4,3.6,3.8,4,4.3,4.7,4.9,5,5.5,6,6.5,6.8,7,7.3,7.5,7.8,8,8.4,8.7,9,9.4,9.6,9.8,10],a.IDENTITY_MATRIX=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1],a.LENGTH=a.IDENTITY_MATRIX.length,b.setColor=function(a,b,c,d){return this.reset().adjustColor(a,b,c,d)},b.reset=function(){return this.copy(a.IDENTITY_MATRIX)},b.adjustColor=function(a,b,c,d){return this.adjustHue(d),this.adjustContrast(b),this.adjustBrightness(a),this.adjustSaturation(c)},b.adjustBrightness=function(a){return 0==a||isNaN(a)?this:(a=this._cleanValue(a,255),this._multiplyMatrix([1,0,0,0,a,0,1,0,0,a,0,0,1,0,a,0,0,0,1,0,0,0,0,0,1]),this)},b.adjustContrast=function(b){if(0==b||isNaN(b))return this;b=this._cleanValue(b,100);var c;return 0>b?c=127+b/100*127:(c=b%1,c=0==c?a.DELTA_INDEX[b]:a.DELTA_INDEX[b<<0]*(1-c)+a.DELTA_INDEX[(b<<0)+1]*c,c=127*c+127),this._multiplyMatrix([c/127,0,0,0,.5*(127-c),0,c/127,0,0,.5*(127-c),0,0,c/127,0,.5*(127-c),0,0,0,1,0,0,0,0,0,1]),this},b.adjustSaturation=function(a){if(0==a||isNaN(a))return this;a=this._cleanValue(a,100);var b=1+(a>0?3*a/100:a/100),c=.3086,d=.6094,e=.082;return this._multiplyMatrix([c*(1-b)+b,d*(1-b),e*(1-b),0,0,c*(1-b),d*(1-b)+b,e*(1-b),0,0,c*(1-b),d*(1-b),e*(1-b)+b,0,0,0,0,0,1,0,0,0,0,0,1]),this},b.adjustHue=function(a){if(0==a||isNaN(a))return this;a=this._cleanValue(a,180)/180*Math.PI;var b=Math.cos(a),c=Math.sin(a),d=.213,e=.715,f=.072;return this._multiplyMatrix([d+b*(1-d)+c*-d,e+b*-e+c*-e,f+b*-f+c*(1-f),0,0,d+b*-d+.143*c,e+b*(1-e)+.14*c,f+b*-f+c*-.283,0,0,d+b*-d+c*-(1-d),e+b*-e+c*e,f+b*(1-f)+c*f,0,0,0,0,0,1,0,0,0,0,0,1]),this},b.concat=function(b){return b=this._fixMatrix(b),b.length!=a.LENGTH?this:(this._multiplyMatrix(b),this)},b.clone=function(){return(new a).copy(this)},b.toArray=function(){for(var b=[],c=0,d=a.LENGTH;d>c;c++)b[c]=this[c];return b},b.copy=function(b){for(var c=a.LENGTH,d=0;c>d;d++)this[d]=b[d];return this},b.toString=function(){return"[ColorMatrix]"},b._multiplyMatrix=function(a){var b,c,d,e=[];for(b=0;5>b;b++){for(c=0;5>c;c++)e[c]=this[c+5*b];for(c=0;5>c;c++){var f=0;for(d=0;5>d;d++)f+=a[c+5*d]*e[d];this[c+5*b]=f}}},b._cleanValue=function(a,b){return Math.min(b,Math.max(-b,a))},b._fixMatrix=function(b){return b instanceof a&&(b=b.toArray()),b.lengtha.LENGTH&&(b=b.slice(0,a.LENGTH)),b},createjs.ColorMatrix=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.matrix=a}var b=createjs.extend(a,createjs.Filter);b.toString=function(){return"[ColorMatrixFilter]"},b.clone=function(){return new a(this.matrix)},b._applyFilter=function(a){for(var b,c,d,e,f=a.data,g=f.length,h=this.matrix,i=h[0],j=h[1],k=h[2],l=h[3],m=h[4],n=h[5],o=h[6],p=h[7],q=h[8],r=h[9],s=h[10],t=h[11],u=h[12],v=h[13],w=h[14],x=h[15],y=h[16],z=h[17],A=h[18],B=h[19],C=0;g>C;C+=4)b=f[C],c=f[C+1],d=f[C+2],e=f[C+3],f[C]=b*i+c*j+d*k+e*l+m,f[C+1]=b*n+c*o+d*p+e*q+r,f[C+2]=b*s+c*t+d*u+e*v+w,f[C+3]=b*x+c*y+d*z+e*A+B;return!0},createjs.ColorMatrixFilter=createjs.promote(a,"Filter")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"Touch cannot be instantiated"}a.isSupported=function(){return!!("ontouchstart"in window||window.navigator.msPointerEnabled&&window.navigator.msMaxTouchPoints>0||window.navigator.pointerEnabled&&window.navigator.maxTouchPoints>0)},a.enable=function(b,c,d){return b&&b.canvas&&a.isSupported()?b.__touch?!0:(b.__touch={pointers:{},multitouch:!c,preventDefault:!d,count:0},"ontouchstart"in window?a._IOS_enable(b):(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&a._IE_enable(b),!0):!1},a.disable=function(b){b&&("ontouchstart"in window?a._IOS_disable(b):(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&a._IE_disable(b),delete b.__touch)},a._IOS_enable=function(b){var c=b.canvas,d=b.__touch.f=function(c){a._IOS_handleEvent(b,c)};c.addEventListener("touchstart",d,!1),c.addEventListener("touchmove",d,!1),c.addEventListener("touchend",d,!1),c.addEventListener("touchcancel",d,!1)},a._IOS_disable=function(a){var b=a.canvas;if(b){var c=a.__touch.f;b.removeEventListener("touchstart",c,!1),b.removeEventListener("touchmove",c,!1),b.removeEventListener("touchend",c,!1),b.removeEventListener("touchcancel",c,!1)}},a._IOS_handleEvent=function(a,b){if(a){a.__touch.preventDefault&&b.preventDefault&&b.preventDefault();for(var c=b.changedTouches,d=b.type,e=0,f=c.length;f>e;e++){var g=c[e],h=g.identifier;g.target==a.canvas&&("touchstart"==d?this._handleStart(a,h,b,g.pageX,g.pageY):"touchmove"==d?this._handleMove(a,h,b,g.pageX,g.pageY):("touchend"==d||"touchcancel"==d)&&this._handleEnd(a,h,b))}}},a._IE_enable=function(b){var c=b.canvas,d=b.__touch.f=function(c){a._IE_handleEvent(b,c)};void 0===window.navigator.pointerEnabled?(c.addEventListener("MSPointerDown",d,!1),window.addEventListener("MSPointerMove",d,!1),window.addEventListener("MSPointerUp",d,!1),window.addEventListener("MSPointerCancel",d,!1),b.__touch.preventDefault&&(c.style.msTouchAction="none")):(c.addEventListener("pointerdown",d,!1),window.addEventListener("pointermove",d,!1),window.addEventListener("pointerup",d,!1),window.addEventListener("pointercancel",d,!1),b.__touch.preventDefault&&(c.style.touchAction="none")),b.__touch.activeIDs={}},a._IE_disable=function(a){var b=a.__touch.f;void 0===window.navigator.pointerEnabled?(window.removeEventListener("MSPointerMove",b,!1),window.removeEventListener("MSPointerUp",b,!1),window.removeEventListener("MSPointerCancel",b,!1),a.canvas&&a.canvas.removeEventListener("MSPointerDown",b,!1)):(window.removeEventListener("pointermove",b,!1),window.removeEventListener("pointerup",b,!1),window.removeEventListener("pointercancel",b,!1),a.canvas&&a.canvas.removeEventListener("pointerdown",b,!1))},a._IE_handleEvent=function(a,b){if(a){a.__touch.preventDefault&&b.preventDefault&&b.preventDefault();var c=b.type,d=b.pointerId,e=a.__touch.activeIDs;if("MSPointerDown"==c||"pointerdown"==c){if(b.srcElement!=a.canvas)return;e[d]=!0,this._handleStart(a,d,b,b.pageX,b.pageY)}else e[d]&&("MSPointerMove"==c||"pointermove"==c?this._handleMove(a,d,b,b.pageX,b.pageY):("MSPointerUp"==c||"MSPointerCancel"==c||"pointerup"==c||"pointercancel"==c)&&(delete e[d],this._handleEnd(a,d,b)))}},a._handleStart=function(a,b,c,d,e){var f=a.__touch;if(f.multitouch||!f.count){var g=f.pointers;g[b]||(g[b]=!0,f.count++,a._handlePointerDown(b,c,d,e))}},a._handleMove=function(a,b,c,d,e){a.__touch.pointers[b]&&a._handlePointerMove(b,c,d,e)},a._handleEnd=function(a,b,c){var d=a.__touch,e=d.pointers;e[b]&&(d.count--,a._handlePointerUp(b,c,!0),delete e[b])},createjs.Touch=a}(),this.createjs=this.createjs||{},function(){"use strict";var a=createjs.EaselJS=createjs.EaselJS||{};a.version="0.8.1",a.buildDate="Thu, 21 May 2015 16:17:39 GMT"}(); \ No newline at end of file +this.createjs=this.createjs||{},createjs.extend=function(a,b){"use strict";function c(){this.constructor=a}return c.prototype=b.prototype,a.prototype=new c},this.createjs=this.createjs||{},createjs.promote=function(a,b){"use strict";var c=a.prototype,d=Object.getPrototypeOf&&Object.getPrototypeOf(c)||c.__proto__;if(d){c[(b+="_")+"constructor"]=d.constructor;for(var e in d)c.hasOwnProperty(e)&&"function"==typeof d[e]&&(c[b+e]=d[e])}return a},this.createjs=this.createjs||{},createjs.indexOf=function(a,b){"use strict";for(var c=0,d=a.length;c=0&&!a.propagationStopped;g--)f[g]._dispatchEvent(a,1+(0==g));for(g=1;g=.97*(a._interval-1)&&a._tick()},a._handleRAF=function(){a._timerId=null,a._setupTick(),a._tick()},a._handleTimeout=function(){a._timerId=null,a._setupTick(),a._tick()},a._setupTick=function(){if(null==a._timerId){var b=a.timingMode||a.useRAF&&a.RAF_SYNCHED;if(b==a.RAF_SYNCHED||b==a.RAF){var c=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame;if(c)return a._timerId=c(b==a.RAF?a._handleRAF:a._handleSynch),void(a._raf=!0)}a._raf=!1,a._timerId=setTimeout(a._handleTimeout,a._interval)}},a._tick=function(){var b=a.paused,c=a._getTime(),d=c-a._lastTime;if(a._lastTime=c,a._ticks++,b&&(a._pausedTicks++,a._pausedTime+=d),a.hasEventListener("tick")){var e=new createjs.Event("tick"),f=a.maxDelta;e.delta=f&&d>f?f:d,e.paused=b,e.time=c,e.runTime=c-a._pausedTime,a.dispatchEvent(e)}for(a._tickTimes.unshift(a._getTime()-c);a._tickTimes.length>100;)a._tickTimes.pop();for(a._times.unshift(c);a._times.length>100;)a._times.pop()};var b=window.performance&&(performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow);a._getTime=function(){return(b&&b.call(performance)||(new Date).getTime())-a._startTime},createjs.Ticker=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"UID cannot be instantiated"}a._nextID=0,a.get=function(){return a._nextID++},createjs.UID=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f,g,h,i,j,k){this.Event_constructor(a,b,c),this.stageX=d,this.stageY=e,this.rawX=null==i?d:i,this.rawY=null==j?e:j,this.nativeEvent=f,this.pointerID=g,this.primary=!!h,this.relatedTarget=k}var b=createjs.extend(a,createjs.Event);b._get_localX=function(){return this.currentTarget.globalToLocal(this.rawX,this.rawY).x},b._get_localY=function(){return this.currentTarget.globalToLocal(this.rawX,this.rawY).y},b._get_isTouch=function(){return-1!==this.pointerID};try{Object.defineProperties(b,{localX:{get:b._get_localX},localY:{get:b._get_localY},isTouch:{get:b._get_isTouch}})}catch(a){}b.clone=function(){return new a(this.type,this.bubbles,this.cancelable,this.stageX,this.stageY,this.nativeEvent,this.pointerID,this.primary,this.rawX,this.rawY)},b.toString=function(){return"[MouseEvent (type="+this.type+" stageX="+this.stageX+" stageY="+this.stageY+")]"},createjs.MouseEvent=createjs.promote(a,"Event")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e,f){this.setValues(a,b,c,d,e,f)}var b=a.prototype;a.DEG_TO_RAD=Math.PI/180,a.identity=null,b.setValues=function(a,b,c,d,e,f){return this.a=null==a?1:a,this.b=b||0,this.c=c||0,this.d=null==d?1:d,this.tx=e||0,this.ty=f||0,this},b.append=function(a,b,c,d,e,f){var g=this.a,h=this.b,i=this.c,j=this.d;return 1==a&&0==b&&0==c&&1==d||(this.a=g*a+i*b,this.b=h*a+j*b,this.c=g*c+i*d,this.d=h*c+j*d),this.tx=g*e+i*f+this.tx,this.ty=h*e+j*f+this.ty,this},b.prepend=function(a,b,c,d,e,f){var g=this.a,h=this.c,i=this.tx;return this.a=a*g+c*this.b,this.b=b*g+d*this.b,this.c=a*h+c*this.d,this.d=b*h+d*this.d,this.tx=a*i+c*this.ty+e,this.ty=b*i+d*this.ty+f,this},b.appendMatrix=function(a){return this.append(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.prependMatrix=function(a){return this.prepend(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.appendTransform=function(b,c,d,e,f,g,h,i,j){if(f%360)var k=f*a.DEG_TO_RAD,l=Math.cos(k),m=Math.sin(k);else l=1,m=0;return g||h?(g*=a.DEG_TO_RAD,h*=a.DEG_TO_RAD,this.append(Math.cos(h),Math.sin(h),-Math.sin(g),Math.cos(g),b,c),this.append(l*d,m*d,-m*e,l*e,0,0)):this.append(l*d,m*d,-m*e,l*e,b,c),(i||j)&&(this.tx-=i*this.a+j*this.c,this.ty-=i*this.b+j*this.d),this},b.prependTransform=function(b,c,d,e,f,g,h,i,j){if(f%360)var k=f*a.DEG_TO_RAD,l=Math.cos(k),m=Math.sin(k);else l=1,m=0;return(i||j)&&(this.tx-=i,this.ty-=j),g||h?(g*=a.DEG_TO_RAD,h*=a.DEG_TO_RAD,this.prepend(l*d,m*d,-m*e,l*e,0,0),this.prepend(Math.cos(h),Math.sin(h),-Math.sin(g),Math.cos(g),b,c)):this.prepend(l*d,m*d,-m*e,l*e,b,c),this},b.rotate=function(b){b*=a.DEG_TO_RAD;var c=Math.cos(b),d=Math.sin(b),e=this.a,f=this.b;return this.a=e*c+this.c*d,this.b=f*c+this.d*d,this.c=-e*d+this.c*c,this.d=-f*d+this.d*c,this},b.skew=function(b,c){return b*=a.DEG_TO_RAD,c*=a.DEG_TO_RAD,this.append(Math.cos(c),Math.sin(c),-Math.sin(b),Math.cos(b),0,0),this},b.scale=function(a,b){return this.a*=a,this.b*=a,this.c*=b,this.d*=b,this},b.translate=function(a,b){return this.tx+=this.a*a+this.c*b,this.ty+=this.b*a+this.d*b,this},b.identity=function(){return this.a=this.d=1,this.b=this.c=this.tx=this.ty=0,this},b.invert=function(){var a=this.a,b=this.b,c=this.c,d=this.d,e=this.tx,f=a*d-b*c;return this.a=d/f,this.b=-b/f,this.c=-c/f,this.d=a/f,this.tx=(c*this.ty-d*e)/f,this.ty=-(a*this.ty-b*e)/f,this},b.isIdentity=function(){return 0===this.tx&&0===this.ty&&1===this.a&&0===this.b&&0===this.c&&1===this.d},b.equals=function(a){return this.tx===a.tx&&this.ty===a.ty&&this.a===a.a&&this.b===a.b&&this.c===a.c&&this.d===a.d},b.transformPoint=function(a,b,c){return c=c||{},c.x=a*this.a+b*this.c+this.tx,c.y=a*this.b+b*this.d+this.ty,c},b.decompose=function(b){null==b&&(b={}),b.x=this.tx,b.y=this.ty,b.scaleX=Math.sqrt(this.a*this.a+this.b*this.b),b.scaleY=Math.sqrt(this.c*this.c+this.d*this.d);var c=Math.atan2(-this.c,this.d),d=Math.atan2(this.b,this.a);return Math.abs(1-c/d)<1e-5?(b.rotation=d/a.DEG_TO_RAD,this.a<0&&this.d>=0&&(b.rotation+=b.rotation<=0?180:-180),b.skewX=b.skewY=0):(b.skewX=c/a.DEG_TO_RAD,b.skewY=d/a.DEG_TO_RAD),b},b.copy=function(a){return this.setValues(a.a,a.b,a.c,a.d,a.tx,a.ty)},b.clone=function(){return new a(this.a,this.b,this.c,this.d,this.tx,this.ty)},b.toString=function(){return"[Matrix2D (a="+this.a+" b="+this.b+" c="+this.c+" d="+this.d+" tx="+this.tx+" ty="+this.ty+")]"},a.identity=new a,createjs.Matrix2D=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d,e){this.setValues(a,b,c,d,e)}var b=a.prototype;b.setValues=function(a,b,c,d,e){return this.visible=null==a||!!a,this.alpha=null==b?1:b,this.shadow=c,this.compositeOperation=d,this.matrix=e||this.matrix&&this.matrix.identity()||new createjs.Matrix2D,this},b.append=function(a,b,c,d,e){return this.alpha*=b,this.shadow=c||this.shadow,this.compositeOperation=d||this.compositeOperation,this.visible=this.visible&&a,e&&this.matrix.appendMatrix(e),this},b.prepend=function(a,b,c,d,e){return this.alpha*=b,this.shadow=this.shadow||c,this.compositeOperation=this.compositeOperation||d,this.visible=this.visible&&a,e&&this.matrix.prependMatrix(e),this},b.identity=function(){return this.visible=!0,this.alpha=1,this.shadow=this.compositeOperation=null,this.matrix.identity(),this},b.clone=function(){return new a(this.alpha,this.shadow,this.compositeOperation,this.visible,this.matrix.clone())},createjs.DisplayProps=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.setValues(a,b)}var b=a.prototype;b.setValues=function(a,b){return this.x=a||0,this.y=b||0,this},b.copy=function(a){return this.x=a.x,this.y=a.y,this},b.clone=function(){return new a(this.x,this.y)},b.toString=function(){return"[Point (x="+this.x+" y="+this.y+")]"},createjs.Point=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c,d){this.setValues(a,b,c,d)}var b=a.prototype;b.setValues=function(a,b,c,d){return this.x=a||0,this.y=b||0,this.width=c||0,this.height=d||0,this},b.extend=function(a,b,c,d){return c=c||0,d=d||0,a+c>this.x+this.width&&(this.width=a+c-this.x),b+d>this.y+this.height&&(this.height=b+d-this.y),a=this.x&&a+c<=this.x+this.width&&b>=this.y&&b+d<=this.y+this.height},b.union=function(a){return this.clone().extend(a.x,a.y,a.width,a.height)},b.intersection=function(b){var c=b.x,d=b.y,e=c+b.width,f=d+b.height;return this.x>c&&(c=this.x),this.y>d&&(d=this.y),this.x+this.width0)for(e=this._images=[],b=0;b=a)break a;b++,this._frames.push({image:i,rect:new createjs.Rectangle(m,l,c,d),regX:this._regX,regY:this._regY}),m+=c+e}l+=d+e}this._numFrames=b}},createjs.SpriteSheet=createjs.promote(a,"EventDispatcher")}(),this.createjs=this.createjs||{},function(){"use strict";function a(){this.command=null,this._stroke=null,this._strokeStyle=null,this._oldStrokeStyle=null,this._strokeDash=null,this._oldStrokeDash=null,this._strokeIgnoreScale=!1,this._fill=null,this._instructions=[],this._commitIndex=0,this._activeInstructions=[],this._dirty=!1,this._storeIndex=0,this.clear()}function b(a,b,d,e,f,g,h,i){var j=c(g,e,f),k=c(h,e,f),l=-Math.sin(k-j)*(Math.sqrt(4+3*Math.pow(Math.tan((k-j)/2),2))-1)/3,m=e*f/Math.sqrt(Math.pow(f*Math.cos(g),2)+Math.pow(e*Math.sin(g),2)),n=b+m*Math.cos(g),o=d+m*Math.sin(g),p=e*f/Math.sqrt(Math.pow(f*Math.cos(h),2)+Math.pow(e*Math.sin(h),2)),q=b+p*Math.cos(h),r=d+p*Math.sin(h),s=n-l*Math.sin(-j)*e,t=o-l*Math.cos(-j)*f,u=q+l*Math.sin(-k)*e,v=r+l*Math.cos(-k)*f;return"radii"===i||"chord"===i?a.lineTo(n,o):a.moveTo(n,o),a.bezierCurveTo(s,t,u,v,q,r),{x:n,y:o}}function c(a,b,c){var e,f=Math.cos(a),g=Math.sin(a);if(d(b,c)||d(Math.abs(f),0)||d(Math.abs(g),0))return a;var h=b*Math.tan(a)/c;return f>0&&g>0?e=Math.atan(h):f<0&&g>0?e=Math.PI+Math.atan(h):f<0&&g<0?e=Math.PI+Math.atan(h):f>0&&g<0&&(e=2*Math.PI+Math.atan(h)),e}function d(a,b){var c=.001,d=2.220446049250313e-16;if(a===b)return!0;if(isNaN(a)||isNaN(b))return!1;if(isFinite(a)&&isFinite(b)){var e=Math.abs(a-b);return e>8&255,a=a>>16&255),null==d?"rgb("+a+","+b+","+c+")":"rgba("+a+","+b+","+c+","+d+")"},a.getHSL=function(a,b,c,d){return null==d?"hsl("+a%360+","+b+"%,"+c+"%)":"hsla("+a%360+","+b+"%,"+c+"%,"+d+")"},a.BASE_64={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,a:26,b:27,c:28,d:29,e:30,f:31,g:32,h:33,i:34,j:35,k:36,l:37,m:38,n:39,o:40,p:41,q:42,r:43,s:44,t:45,u:46,v:47,w:48,x:49,y:50,z:51,0:52,1:53,2:54,3:55,4:56,5:57,6:58,7:59,8:60,9:61,"+":62,"/":63},a.STROKE_CAPS_MAP=["butt","round","square"],a.STROKE_JOINTS_MAP=["miter","round","bevel"];var g=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");g.getContext&&(a._ctx=g.getContext("2d"),g.width=g.height=1),e.getInstructions=function(){return this._updateInstructions(),this._instructions};try{Object.defineProperties(e,{instructions:{get:e.getInstructions}})}catch(a){}e.isEmpty=function(){return!(this._instructions.length||this._activeInstructions.length)},e.draw=function(a,b){this._updateInstructions();for(var c=this._instructions,d=this._storeIndex,e=c.length;d>3,n=c[m];if(!n||3&l)throw"bad path data (@"+e+"): "+k;var o=d[m];m||(h=i=0),g.length=0,e++;for(var p=2+(l>>2&1),q=0;q>5?-1:1;r=(31&r)<<6|j[b.charAt(e+1)],3==p&&(r=r<<6|j[b.charAt(e+2)]),r=s*r/10,q%2?h=r+=h:i=r+=i,g[q]=r,e+=p}n.apply(this,g)}return this},e.store=function(){return this._updateInstructions(!0),this._storeIndex=this._instructions.length,this},e.unstore=function(){return this._storeIndex=0,this},e.clone=function(){var b=new a;return b.command=this.command,b._stroke=this._stroke,b._strokeStyle=this._strokeStyle,b._strokeDash=this._strokeDash,b._strokeIgnoreScale=this._strokeIgnoreScale,b._fill=this._fill,b._instructions=this._instructions.slice(),b._commitIndex=this._commitIndex,b._activeInstructions=this._activeInstructions.slice(),b._dirty=this._dirty,b._storeIndex=this._storeIndex,b},e.toString=function(){return"[Graphics]"},e.mt=e.moveTo,e.lt=e.lineTo,e.at=e.arcTo,e.bt=e.bezierCurveTo,e.qt=e.quadraticCurveTo,e.a=e.arc,e.ea=e.ellipticalArc,e.r=e.rect,e.cp=e.closePath,e.c=e.clear,e.f=e.beginFill,e.lf=e.beginLinearGradientFill,e.rf=e.beginRadialGradientFill,e.bf=e.beginBitmapFill,e.ef=e.endFill,e.ss=e.setStrokeStyle,e.sd=e.setStrokeDash,e.s=e.beginStroke,e.ls=e.beginLinearGradientStroke,e.rs=e.beginRadialGradientStroke,e.bs=e.beginBitmapStroke,e.es=e.endStroke,e.dr=e.drawRect,e.rr=e.drawRoundRect,e.rc=e.drawRoundRectComplex,e.dc=e.drawCircle,e.de=e.drawEllipse,e.dp=e.drawPolyStar,e.p=e.decodePath,e._updateInstructions=function(b){var c=this._instructions,d=this._activeInstructions,e=this._commitIndex;if(this._dirty&&d.length){c.length=e,c.push(a.beginCmd);var f=d.length,g=c.length;c.length=g+f;for(var h=0;h=2){(this.style=a._ctx.createPattern(b,c||"")).props={image:b,repetition:c,type:"bitmap"}}return this},e.path=!1,e=(f.Stroke=function(a,b){this.style=a,this.ignoreScale=b}).prototype,e.exec=function(a){this.style&&(a.strokeStyle=this.style,this.ignoreScale&&(a.save(),a.setTransform(1,0,0,1,0,0)),a.stroke(),this.ignoreScale&&a.restore())},e.linearGradient=f.Fill.prototype.linearGradient,e.radialGradient=f.Fill.prototype.radialGradient,e.bitmap=f.Fill.prototype.bitmap,e.path=!1,e=(f.StrokeStyle=function(a,b,c,d,e){this.width=a,this.caps=b,this.joints=c,this.miterLimit=d,this.ignoreScale=e}).prototype,e.exec=function(b){b.lineWidth=null==this.width?"1":this.width,b.lineCap=null==this.caps?"butt":isNaN(this.caps)?this.caps:a.STROKE_CAPS_MAP[this.caps], +b.lineJoin=null==this.joints?"miter":isNaN(this.joints)?this.joints:a.STROKE_JOINTS_MAP[this.joints],b.miterLimit=null==this.miterLimit?"10":this.miterLimit,b.ignoreScale=null!=this.ignoreScale&&this.ignoreScale},e.path=!1,(f.StrokeDash=function(a,b){this.segments=a,this.offset=b||0}).prototype.exec=function(a){a.setLineDash&&(a.setLineDash(this.segments||f.StrokeDash.EMPTY_SEGMENTS),a.lineDashOffset=this.offset||0)},f.StrokeDash.EMPTY_SEGMENTS=[],(f.RoundRect=function(a,b,c,d,e,f,g,h){this.x=a,this.y=b,this.w=c,this.h=d,this.radiusTL=e,this.radiusTR=f,this.radiusBR=g,this.radiusBL=h}).prototype.exec=function(a){var b=(ib&&(k=b),l<0&&(l*=d=-1),l>b&&(l=b),m<0&&(m*=e=-1),m>b&&(m=b),n<0&&(n*=f=-1),n>b&&(n=b),a.moveTo(g+i-l,h),a.arcTo(g+i+l*d,h-l*d,g+i,h+l,l),a.lineTo(g+i,h+j-m),a.arcTo(g+i+m*e,h+j+m*e,g+i-m,h+j,m),a.lineTo(g+n,h+j),a.arcTo(g-n*f,h+j+n*f,g,h+j-n,n),a.lineTo(g,h+k),a.arcTo(g-k*c,h-k*c,g+k,h,k),a.closePath()},(f.Circle=function(a,b,c){this.x=a,this.y=b,this.radius=c}).prototype.exec=function(a){a.arc(this.x,this.y,this.radius,0,2*Math.PI)},(f.Ellipse=function(a,b,c,d){this.x=a,this.y=b,this.w=c,this.h=d}).prototype.exec=function(a){var b=this.x,c=this.y,d=this.w,e=this.h,f=.5522848,g=d/2*f,h=e/2*f,i=b+d,j=c+e,k=b+d/2,l=c+e/2;a.moveTo(b,l),a.bezierCurveTo(b,l-h,k-g,c,k,c),a.bezierCurveTo(k+g,c,i,l-h,i,l),a.bezierCurveTo(i,l+h,k+g,j,k,j),a.bezierCurveTo(k-g,j,b,l+h,b,l)},(f.PolyStar=function(a,b,c,d,e,f){this.x=a,this.y=b,this.radius=c,this.sides=d,this.pointSize=e,this.angle=f}).prototype.exec=function(a){var b=this.x,c=this.y,d=this.radius,e=(this.angle||0)/180*Math.PI,f=this.sides,g=1-(this.pointSize||0),h=Math.PI/f;a.moveTo(b+Math.cos(e)*d,c+Math.sin(e)*d);for(var i=0;i0&&0!=this.scaleX&&0!=this.scaleY)},b.draw=function(a,b){var c=this.cacheCanvas;if(b||!c)return!1;var d=this._cacheScale;return a.drawImage(c,this._cacheOffsetX+this._filterOffsetX,this._cacheOffsetY+this._filterOffsetY,c.width/d,c.height/d),!0},b.updateContext=function(b){var c=this,d=c.mask,e=c._props.matrix;d&&d.graphics&&!d.graphics.isEmpty()&&(d.getMatrix(e),b.transform(e.a,e.b,e.c,e.d,e.tx,e.ty),d.graphics.drawAsPath(b),b.clip(),e.invert(),b.transform(e.a,e.b,e.c,e.d,e.tx,e.ty)),this.getMatrix(e);var f=e.tx,g=e.ty;a._snapToPixelEnabled&&c.snapToPixel&&(f=f+(f<0?-.5:.5)|0,g=g+(g<0?-.5:.5)|0),b.transform(e.a,e.b,e.c,e.d,f,g),b.globalAlpha*=c.alpha,c.compositeOperation&&(b.globalCompositeOperation=c.compositeOperation),c.shadow&&this._applyShadow(b,c.shadow)},b.cache=function(a,b,c,d,e){e=e||1,this.cacheCanvas||(this.cacheCanvas=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")),this._cacheWidth=c,this._cacheHeight=d,this._cacheOffsetX=a,this._cacheOffsetY=b,this._cacheScale=e,this.updateCache()},b.updateCache=function(b){var c=this.cacheCanvas;if(!c)throw"cache() must be called before updateCache()";var d=this._cacheScale,e=this._cacheOffsetX*d,f=this._cacheOffsetY*d,g=this._cacheWidth,h=this._cacheHeight,i=c.getContext("2d"),j=this._getFilterBounds();e+=this._filterOffsetX=j.x,f+=this._filterOffsetY=j.y,g=Math.ceil(g*d)+j.width,h=Math.ceil(h*d)+j.height,g!=c.width||h!=c.height?(c.width=g,c.height=h):b||i.clearRect(0,0,g+1,h+1),i.save(),i.globalCompositeOperation=b,i.setTransform(d,0,0,d,-e,-f),this.draw(i,!0),this._applyFilters(),i.restore(),this.cacheID=a._nextCacheID++},b.uncache=function(){this._cacheDataURL=this.cacheCanvas=null,this.cacheID=this._cacheOffsetX=this._cacheOffsetY=this._filterOffsetX=this._filterOffsetY=0,this._cacheScale=1},b.getCacheDataURL=function(){return this.cacheCanvas?(this.cacheID!=this._cacheDataURLID&&(this._cacheDataURL=this.cacheCanvas.toDataURL()),this._cacheDataURL):null},b.localToGlobal=function(a,b,c){return this.getConcatenatedMatrix(this._props.matrix).transformPoint(a,b,c||new createjs.Point)},b.globalToLocal=function(a,b,c){return this.getConcatenatedMatrix(this._props.matrix).invert().transformPoint(a,b,c||new createjs.Point)},b.localToLocal=function(a,b,c,d){return d=this.localToGlobal(a,b,d),c.globalToLocal(d.x,d.y,d)},b.setTransform=function(a,b,c,d,e,f,g,h,i){return this.x=a||0,this.y=b||0,this.scaleX=null==c?1:c,this.scaleY=null==d?1:d,this.rotation=e||0,this.skewX=f||0,this.skewY=g||0,this.regX=h||0,this.regY=i||0,this},b.getMatrix=function(a){var b=this,c=a&&a.identity()||new createjs.Matrix2D;return b.transformMatrix?c.copy(b.transformMatrix):c.appendTransform(b.x,b.y,b.scaleX,b.scaleY,b.rotation,b.skewX,b.skewY,b.regX,b.regY)},b.getConcatenatedMatrix=function(a){for(var b=this,c=this.getMatrix(a);b=b.parent;)c.prependMatrix(b.getMatrix(b._props.matrix));return c},b.getConcatenatedDisplayProps=function(a){a=a?a.identity():new createjs.DisplayProps;var b=this,c=b.getMatrix(a.matrix);do{a.prepend(b.visible,b.alpha,b.shadow,b.compositeOperation),b!=this&&c.prependMatrix(b.getMatrix(b._props.matrix))}while(b=b.parent);return a},b.hitTest=function(b,c){var d=a._hitTestContext;d.setTransform(1,0,0,1,-b,-c),this.draw(d);var e=this._testHit(d);return d.setTransform(1,0,0,1,0,0),d.clearRect(0,0,2,2),e},b.set=function(a){for(var b in a)this[b]=a[b];return this},b.getBounds=function(){if(this._bounds)return this._rectangle.copy(this._bounds);var a=this.cacheCanvas;if(a){var b=this._cacheScale;return this._rectangle.setValues(this._cacheOffsetX,this._cacheOffsetY,a.width/b,a.height/b)}return null},b.getTransformedBounds=function(){return this._getBounds()},b.setBounds=function(a,b,c,d){null==a&&(this._bounds=a),this._bounds=(this._bounds||new createjs.Rectangle).setValues(a,b,c,d)},b.clone=function(){return this._cloneProps(new a)},b.toString=function(){return"[DisplayObject (name="+this.name+")]"},b._cloneProps=function(a){return a.alpha=this.alpha,a.mouseEnabled=this.mouseEnabled,a.tickEnabled=this.tickEnabled,a.name=this.name,a.regX=this.regX,a.regY=this.regY,a.rotation=this.rotation,a.scaleX=this.scaleX,a.scaleY=this.scaleY,a.shadow=this.shadow,a.skewX=this.skewX,a.skewY=this.skewY,a.visible=this.visible,a.x=this.x,a.y=this.y,a.compositeOperation=this.compositeOperation,a.snapToPixel=this.snapToPixel,a.filters=null==this.filters?null:this.filters.slice(0),a.mask=this.mask,a.hitArea=this.hitArea,a.cursor=this.cursor,a._bounds=this._bounds,a},b._applyShadow=function(a,b){b=b||Shadow.identity,a.shadowColor=b.color,a.shadowOffsetX=b.offsetX,a.shadowOffsetY=b.offsetY,a.shadowBlur=b.blur},b._tick=function(a){var b=this._listeners;b&&b.tick&&(a.target=null,a.propagationStopped=a.immediatePropagationStopped=!1,this.dispatchEvent(a))},b._testHit=function(b){try{var c=b.getImageData(0,0,1,1).data[3]>1}catch(b){if(!a.suppressCrossDomainErrors)throw"An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images."}return c},b._applyFilters=function(){if(this.filters&&0!=this.filters.length&&this.cacheCanvas)for(var a=this.filters.length,b=this.cacheCanvas.getContext("2d"),c=this.cacheCanvas.width,d=this.cacheCanvas.height,e=0;ep&&(p=d),(d=i+k+m)p&&(p=d),(d=k+m)p&&(p=d),(e=j+n)r&&(r=e),(e=j+l+n)r&&(r=e),(e=l+n)r&&(r=e),a.setValues(o,q,p-o,r-q)},b._hasMouseEventListener=function(){for(var b=a._MOUSE_EVENTS,c=0,d=b.length;c0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;for(var c=this.children.slice(),d=0,e=c.length;d1){for(var c=0;cthis.children.length)return arguments[c-2];if(c>2){for(var e=0;e1){for(var c=!0,d=0;d1){for(var c=[],d=0;dthis.children.length-1)return!1;var f=this.children[a];return f&&(f.parent=null),this.children.splice(a,1),f.dispatchEvent("removed"),!0},b.removeAllChildren=function(){for(var a=this.children;a.length;)this.removeChildAt(0)},b.getChildAt=function(a){return this.children[a]},b.getChildByName=function(a){for(var b=this.children,c=0,d=b.length;c=d)){for(var e=0;e0,1==c),d},b.getObjectUnderPoint=function(a,b,c){var d=this.localToGlobal(a,b);return this._getObjectsUnderPoint(d.x,d.y,null,c>0,1==c)},b.getBounds=function(){return this._getBounds(null,!0)},b.getTransformedBounds=function(){return this._getBounds()},b.clone=function(b){var c=this._cloneProps(new a);return b&&this._cloneChildren(c),c},b.toString=function(){return"[Container (name="+this.name+")]"},b._tick=function(a){if(this.tickChildren)for(var b=this.children.length-1;b>=0;b--){var c=this.children[b];c.tickEnabled&&c._tick&&c._tick(a)}this.DisplayObject__tick(a)},b._cloneChildren=function(a){a.children.length&&a.removeAllChildren();for(var b=a.children,c=0,d=this.children.length;c=0;l--){var m=j[l],n=m.hitArea;if(m.visible&&(n||m.isVisible())&&(!e||m.mouseEnabled)&&(n||this._testMask(m,b,c)))if(!n&&m instanceof a){var o=m._getObjectsUnderPoint(b,c,d,e,f,g+1);if(!d&&o)return e&&!this.mouseChildren?this:o}else{if(e&&!f&&!m._hasMouseEventListener())continue;var p=m.getConcatenatedDisplayProps(m._props);if(h=p.matrix,n&&(h.appendMatrix(n.getMatrix(n._props.matrix)),p.alpha=n.alpha),i.globalAlpha=p.alpha,i.setTransform(h.a,h.b,h.c,h.d,h.tx-b,h.ty-c),(n||m).draw(i),!this._testHit(i))continue;if(i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,2,2),!d)return e&&!this.mouseChildren?this:m;d.push(m)}}return null},b._testMask=function(a,b,c){var d=a.mask;if(!d||!d.graphics||d.graphics.isEmpty())return!0;var e=this._props.matrix,f=a.parent;e=f?f.getConcatenatedMatrix(e):e.identity(),e=d.getMatrix(d._props.matrix).prependMatrix(e);var g=createjs.DisplayObject._hitTestContext;return g.setTransform(e.a,e.b,e.c,e.d,e.tx-b,e.ty-c),d.graphics.drawAsPath(g),g.fillStyle="#000",g.fill(),!!this._testHit(g)&&(g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,2,2),!0)},b._getBounds=function(a,b){var c=this.DisplayObject_getBounds();if(c)return this._transformBounds(c,a,b);var d=this._props.matrix;d=b?d.identity():this.getMatrix(d),a&&d.prependMatrix(a);for(var e=this.children.length,f=null,g=0;g=0&&d>=0&&c<=f-1&&d<=g-1)?(h.x=c,h.y=d):this.mouseMoveOutside&&(h.x=c<0?0:c>f-1?f-1:c,h.y=d<0?0:d>g-1?g-1:d),h.posEvtObj=b,h.rawX=c,h.rawY=d,a!==this._primaryPointerID&&-1!==a||(this.mouseX=h.x,this.mouseY=h.y,this.mouseInBounds=h.inBounds)},b._handleMouseUp=function(a){this._handlePointerUp(-1,a,!1)},b._handlePointerUp=function(a,b,c,d){var e=this._nextStage,f=this._getPointerData(a);if(!this._prevStage||void 0!==d){var g=null,h=f.target;d||!h&&!e||(g=this._getObjectsUnderPoint(f.x,f.y,null,!0)),f.down&&(this._dispatchMouseEvent(this,"stagemouseup",!1,a,f,b,g),f.down=!1),g==h&&this._dispatchMouseEvent(h,"click",!0,a,f,b),this._dispatchMouseEvent(h,"pressup",!0,a,f,b),c?(a==this._primaryPointerID&&(this._primaryPointerID=null),delete this._pointerData[a]):f.target=null,e&&e._handlePointerUp(a,b,c,d||g&&this)}},b._handleMouseDown=function(a){this._handlePointerDown(-1,a,a.pageX,a.pageY)},b._handlePointerDown=function(a,b,c,d,e){this.preventSelection&&b.preventDefault(),null!=this._primaryPointerID&&-1!==a||(this._primaryPointerID=a),null!=d&&this._updatePointerPosition(a,b,c,d);var f=null,g=this._nextStage,h=this._getPointerData(a);e||(f=h.target=this._getObjectsUnderPoint(h.x,h.y,null,!0)),h.inBounds&&(this._dispatchMouseEvent(this,"stagemousedown",!1,a,h,b,f),h.down=!0),this._dispatchMouseEvent(f,"mousedown",!0,a,h,b),g&&g._handlePointerDown(a,b,c,d,e||f&&this)},b._testMouseOver=function(a,b,c){if(!this._prevStage||void 0!==b){var d=this._nextStage;if(!this._mouseOverIntervalID)return void(d&&d._testMouseOver(a,b,c));var e=this._getPointerData(-1);if(e&&(a||this.mouseX!=this._mouseOverX||this.mouseY!=this._mouseOverY||!this.mouseInBounds)){var f,g,h,i=e.posEvtObj,j=c||i&&i.target==this.canvas,k=null,l=-1,m="";!b&&(a||this.mouseInBounds&&j)&&(k=this._getObjectsUnderPoint(this.mouseX,this.mouseY,null,!0),this._mouseOverX=this.mouseX,this._mouseOverY=this.mouseY);var n=this._mouseOverTarget||[],o=n[n.length-1],p=this._mouseOverTarget=[];for(f=k;f;)p.unshift(f),m||(m=f.cursor),f=f.parent;for(this.canvas.style.cursor=m,!b&&c&&(c.canvas.style.cursor=m),g=0,h=p.length;gl;g--)this._dispatchMouseEvent(n[g],"rollout",!1,-1,e,i,k);for(g=p.length-1;g>l;g--)this._dispatchMouseEvent(p[g],"rollover",!1,-1,e,i,o);o!=k&&this._dispatchMouseEvent(k,"mouseover",!0,-1,e,i,o),d&&d._testMouseOver(a,b||k&&this,c||j&&this)}}},b._handleDoubleClick=function(a,b){var c=null,d=this._nextStage,e=this._getPointerData(-1);b||(c=this._getObjectsUnderPoint(e.x,e.y,null,!0),this._dispatchMouseEvent(c,"dblclick",!0,-1,e,a)),d&&d._handleDoubleClick(a,b||c&&this)},b._dispatchMouseEvent=function(a,b,c,d,e,f,g){if(a&&(c||a.hasEventListener(b))){var h=new createjs.MouseEvent(b,c,!1,e.x,e.y,f,d,d===this._primaryPointerID||-1===d,e.rawX,e.rawY,g);a.dispatchEvent(h)}},createjs.Stage=createjs.promote(a,"Container")}(),this.createjs=this.createjs||{},function(){function a(a){this.DisplayObject_constructor(),"string"==typeof a?(this.image=document.createElement("img"),this.image.src=a):this.image=a,this.sourceRect=null}var b=createjs.extend(a,createjs.DisplayObject);b.initialize=a,b.isVisible=function(){var a=this.image,b=this.cacheCanvas||a&&(a.naturalWidth||a.getContext||a.readyState>=2);return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&b)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b)||!this.image)return!0;var c=this.image,d=this.sourceRect;if(d){var e=d.x,f=d.y,g=e+d.width,h=f+d.height,i=0,j=0,k=c.width,l=c.height;e<0&&(i-=e,e=0),g>k&&(g=k),f<0&&(j-=f,f=0),h>l&&(h=l),a.drawImage(c,e,f,g-e,h-f,i,j,g-e,h-f)}else a.drawImage(c,0,0);return!0},b.getBounds=function(){var a=this.DisplayObject_getBounds();if(a)return a;var b=this.image,c=this.sourceRect||b;return b&&(b.naturalWidth||b.getContext||b.readyState>=2)?this._rectangle.setValues(0,0,c.width,c.height):null},b.clone=function(){var b=new a(this.image);return this.sourceRect&&(b.sourceRect=this.sourceRect.clone()),this._cloneProps(b),b},b.toString=function(){return"[Bitmap (name="+this.name+")]"},createjs.Bitmap=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.DisplayObject_constructor(),this.currentFrame=0,this.currentAnimation=null,this.paused=!0,this.spriteSheet=a,this.currentAnimationFrame=0,this.framerate=0,this._animation=null,this._currentFrame=null,this._skipAdvance=!1,null!=b&&this.gotoAndPlay(b)}var b=createjs.extend(a,createjs.DisplayObject);b.initialize=a,b.isVisible=function(){var a=this.cacheCanvas||this.spriteSheet.complete;return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;this._normalizeFrame();var c=this.spriteSheet.getFrame(0|this._currentFrame);if(!c)return!1;var d=c.rect;return d.width&&d.height&&a.drawImage(c.image,d.x,d.y,d.width,d.height,-c.regX,-c.regY,d.width,d.height),!0},b.play=function(){this.paused=!1},b.stop=function(){this.paused=!0},b.gotoAndPlay=function(a){this.paused=!1,this._skipAdvance=!0,this._goto(a)},b.gotoAndStop=function(a){this.paused=!0,this._goto(a)},b.advance=function(a){var b=this.framerate||this.spriteSheet.framerate,c=b&&null!=a?a/(1e3/b):1;this._normalizeFrame(c)},b.getBounds=function(){return this.DisplayObject_getBounds()||this.spriteSheet.getFrameBounds(this.currentFrame,this._rectangle)},b.clone=function(){return this._cloneProps(new a(this.spriteSheet))},b.toString=function(){return"[Sprite (name="+this.name+")]"},b._cloneProps=function(a){return this.DisplayObject__cloneProps(a),a.currentFrame=this.currentFrame,a.currentAnimation=this.currentAnimation,a.paused=this.paused,a.currentAnimationFrame=this.currentAnimationFrame,a.framerate=this.framerate,a._animation=this._animation,a._currentFrame=this._currentFrame,a._skipAdvance=this._skipAdvance,a},b._tick=function(a){this.paused||(this._skipAdvance||this.advance(a&&a.delta),this._skipAdvance=!1),this.DisplayObject__tick(a)},b._normalizeFrame=function(a){a=a||0;var b,c=this._animation,d=this.paused,e=this._currentFrame;if(c){var f=c.speed||1,g=this.currentAnimationFrame;if(b=c.frames.length,g+a*f>=b){var h=c.next;if(this._dispatchAnimationEnd(c,e,d,h,b-1))return;if(h)return this._goto(h,a-(b-g)/f);this.paused=!0,g=c.frames.length-1}else g+=a*f;this.currentAnimationFrame=g,this._currentFrame=c.frames[0|g]}else if(e=this._currentFrame+=a,b=this.spriteSheet.getNumFrames(),e>=b&&b>0&&!this._dispatchAnimationEnd(c,e,d,b-1)&&(this._currentFrame-=b)>=b)return this._normalizeFrame();e=0|this._currentFrame,this.currentFrame!=e&&(this.currentFrame=e,this.dispatchEvent("change"))},b._dispatchAnimationEnd=function(a,b,c,d,e){var f=a?a.name:null;if(this.hasEventListener("animationend")){var g=new createjs.Event("animationend");g.name=f,g.next=d,this.dispatchEvent(g)}var h=this._animation!=a||this._currentFrame!=b;return h||c||!this.paused||(this.currentAnimationFrame=e,h=!0),h},b._goto=function(a,b){if(this.currentAnimationFrame=0,isNaN(a)){var c=this.spriteSheet.getAnimation(a);c&&(this._animation=c,this.currentAnimation=a,this._normalizeFrame(b))}else this.currentAnimation=this._animation=null,this._currentFrame=a,this._normalizeFrame()},createjs.Sprite=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.DisplayObject_constructor(),this.graphics=a||new createjs.Graphics}var b=createjs.extend(a,createjs.DisplayObject);b.isVisible=function(){var a=this.cacheCanvas||this.graphics&&!this.graphics.isEmpty();return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){return!!this.DisplayObject_draw(a,b)||(this.graphics.draw(a,this),!0)},b.clone=function(b){var c=b&&this.graphics?this.graphics.clone():this.graphics;return this._cloneProps(new a(c))},b.toString=function(){return"[Shape (name="+this.name+")]"},createjs.Shape=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c){this.DisplayObject_constructor(),this.text=a,this.font=b,this.color=c,this.textAlign="left",this.textBaseline="top",this.maxWidth=null,this.outline=0,this.lineHeight=0,this.lineWidth=null}var b=createjs.extend(a,createjs.DisplayObject),c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");c.getContext&&(a._workingContext=c.getContext("2d"),c.width=c.height=1),a.H_OFFSETS={start:0,left:0,center:-.5,end:-1,right:-1},a.V_OFFSETS={top:0,hanging:-.01,middle:-.4,alphabetic:-.8,ideographic:-.85,bottom:-1},b.isVisible=function(){var a=this.cacheCanvas||null!=this.text&&""!==this.text;return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY&&a)},b.draw=function(a,b){if(this.DisplayObject_draw(a,b))return!0;var c=this.color||"#000";return this.outline?(a.strokeStyle=c,a.lineWidth=1*this.outline):a.fillStyle=c,this._drawText(this._prepContext(a)),!0},b.getMeasuredWidth=function(){return this._getMeasuredWidth(this.text)},b.getMeasuredLineHeight=function(){return 1.2*this._getMeasuredWidth("M")},b.getMeasuredHeight=function(){return this._drawText(null,{}).height},b.getBounds=function(){var b=this.DisplayObject_getBounds();if(b)return b;if(null==this.text||""===this.text)return null;var c=this._drawText(null,{}),d=this.maxWidth&&this.maxWidththis.lineWidth){var n=l.split(/(\s)/);l=n[0],m=b.measureText(l).width;for(var o=1,p=n.length;othis.lineWidth?(e&&this._drawTextLine(b,l,h*f),d&&d.push(l),m>g&&(g=m),l=n[o+1],m=b.measureText(l).width,h++):(l+=n[o]+n[o+1],m+=q)}}e&&this._drawTextLine(b,l,h*f),d&&d.push(l),c&&null==m&&(m=b.measureText(l).width),m>g&&(g=m),h++}return c&&(c.width=g,c.height=h*f),e||b.restore(),c},b._drawTextLine=function(a,b,c){this.outline?a.strokeText(b,0,c,this.maxWidth||65535):a.fillText(b,0,c,this.maxWidth||65535)},b._getMeasuredWidth=function(b){var c=a._workingContext;c.save();var d=this._prepContext(c).measureText(b).width;return c.restore(),d},createjs.Text=createjs.promote(a,"DisplayObject")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b){this.Container_constructor(),this.text=a||"",this.spriteSheet=b,this.lineHeight=0,this.letterSpacing=0,this.spaceWidth=0,this._oldProps={text:0,spriteSheet:0,lineHeight:0,letterSpacing:0,spaceWidth:0}}var b=createjs.extend(a,createjs.Container);a.maxPoolSize=100,a._spritePool=[],b.draw=function(a,b){this.DisplayObject_draw(a,b)||(this._updateText(),this.Container_draw(a,b))},b.getBounds=function(){return this._updateText(),this.Container_getBounds()},b.isVisible=function(){var a=this.cacheCanvas||this.spriteSheet&&this.spriteSheet.complete&&this.text;return!!(this.visible&&this.alpha>0&&0!==this.scaleX&&0!==this.scaleY&&a)},b.clone=function(){return this._cloneProps(new a(this.text,this.spriteSheet))}, +b.addChild=b.addChildAt=b.removeChild=b.removeChildAt=b.removeAllChildren=function(){},b._cloneProps=function(a){return this.Container__cloneProps(a),a.lineHeight=this.lineHeight,a.letterSpacing=this.letterSpacing,a.spaceWidth=this.spaceWidth,a},b._getFrameIndex=function(a,b){var c,d=b.getAnimation(a);return d||(a!=(c=a.toUpperCase())||a!=(c=a.toLowerCase())||(c=null),c&&(d=b.getAnimation(c))),d&&d.frames[0]},b._getFrame=function(a,b){var c=this._getFrameIndex(a,b);return null==c?c:b.getFrame(c)},b._getLineHeight=function(a){var b=this._getFrame("1",a)||this._getFrame("T",a)||this._getFrame("L",a)||a.getFrame(0);return b?b.rect.height:1},b._getSpaceWidth=function(a){var b=this._getFrame("1",a)||this._getFrame("l",a)||this._getFrame("e",a)||this._getFrame("a",a)||a.getFrame(0);return b?b.rect.width:1},b._updateText=function(){var b,c=0,d=0,e=this._oldProps,f=!1,g=this.spaceWidth,h=this.lineHeight,i=this.spriteSheet,j=a._spritePool,k=this.children,l=0,m=k.length;for(var n in e)e[n]!=this[n]&&(e[n]=this[n],f=!0);if(f){var o=!!this._getFrame(" ",i);o||g||(g=this._getSpaceWidth(i)),h||(h=this._getLineHeight(i));for(var p=0,q=this.text.length;pl;)j.push(b=k.pop()),b.parent=null,m--;j.length>a.maxPoolSize&&(j.length=a.maxPoolSize)}},createjs.BitmapText=createjs.promote(a,"Container")}(),this.createjs=this.createjs||{},function(){"use strict";function a(b,c,d,e){this.Container_constructor(),!a.inited&&a.init(),this.mode=b||a.INDEPENDENT,this.startPosition=c||0,this.loop=d,this.currentFrame=0,this.timeline=new createjs.Timeline(null,e,{paused:!0,position:c,useTicks:!0}),this.paused=!1,this.actionsEnabled=!0,this.autoReset=!0,this.frameBounds=this.frameBounds||null,this.framerate=null,this._synchOffset=0,this._prevPos=-1,this._prevPosition=0,this._t=0,this._managed={}}function b(){throw"MovieClipPlugin cannot be instantiated."}var c=createjs.extend(a,createjs.Container);a.INDEPENDENT="independent",a.SINGLE_FRAME="single",a.SYNCHED="synched",a.inited=!1,a.init=function(){a.inited||(b.install(),a.inited=!0)},c.getLabels=function(){return this.timeline.getLabels()},c.getCurrentLabel=function(){return this._updateTimeline(),this.timeline.getCurrentLabel()},c.getDuration=function(){return this.timeline.duration};try{Object.defineProperties(c,{labels:{get:c.getLabels},currentLabel:{get:c.getCurrentLabel},totalFrames:{get:c.getDuration},duration:{get:c.getDuration}})}catch(a){}c.initialize=a,c.isVisible=function(){return!!(this.visible&&this.alpha>0&&0!=this.scaleX&&0!=this.scaleY)},c.draw=function(a,b){return!!this.DisplayObject_draw(a,b)||(this._updateTimeline(),this.Container_draw(a,b),!0)},c.play=function(){this.paused=!1},c.stop=function(){this.paused=!0},c.gotoAndPlay=function(a){this.paused=!1,this._goto(a)},c.gotoAndStop=function(a){this.paused=!0,this._goto(a)},c.advance=function(b){var c=a.INDEPENDENT;if(this.mode==c){for(var d=this,e=d.framerate;(d=d.parent)&&null==e;)d.mode==c&&(e=d._framerate);this._framerate=e;var f=null!=e&&-1!=e&&null!=b?b/(1e3/e)+this._t:1,g=0|f;for(this._t=f-g;!this.paused&&g--;)this._prevPosition=this._prevPos<0?0:this._prevPosition+1,this._updateTimeline()}},c.clone=function(){throw"MovieClip cannot be cloned."},c.toString=function(){return"[MovieClip (name="+this.name+")]"},c._tick=function(a){this.advance(a&&a.delta),this.Container__tick(a)},c._goto=function(a){var b=this.timeline.resolve(a);null!=b&&(-1==this._prevPos&&(this._prevPos=NaN),this._prevPosition=b,this._t=0,this._updateTimeline())},c._reset=function(){this._prevPos=-1,this._t=this.currentFrame=0,this.paused=!1},c._updateTimeline=function(){var b=this.timeline,c=this.mode!=a.INDEPENDENT;b.loop=null==this.loop||this.loop;var d=c?this.startPosition+(this.mode==a.SINGLE_FRAME?0:this._synchOffset):this._prevPos<0?0:this._prevPosition,e=c||!this.actionsEnabled?createjs.Tween.NONE:null;if(this.currentFrame=b._calcPosition(d),b.setPosition(d,e),this._prevPosition=b._prevPosition,this._prevPos!=b._prevPos){this.currentFrame=this._prevPos=b._prevPos;for(var f in this._managed)this._managed[f]=1;for(var g=b._tweens,h=0,i=g.length;h=0;h--){var n=m[h].id;1==this._managed[n]&&(this.removeChildAt(h),delete this._managed[n])}}},c._setState=function(a,b){if(a)for(var c=a.length-1;c>=0;c--){var d=a[c],e=d.t,f=d.p;for(var g in f)e[g]=f[g];this._addManagedChild(e,b)}},c._addManagedChild=function(b,c){b._off||(this.addChildAt(b,0),b instanceof a&&(b._synchOffset=c,b.mode==a.INDEPENDENT&&b.autoReset&&!this._managed[b.id]&&b._reset()),this._managed[b.id]=2)},c._getBounds=function(a,b){var c=this.DisplayObject_getBounds();return c||(this._updateTimeline(),this.frameBounds&&(c=this._rectangle.copy(this.frameBounds[this.currentFrame]))),c?this._transformBounds(c,a,b):this.Container__getBounds(a,b)},createjs.MovieClip=createjs.promote(a,"Container"),b.priority=100,b.install=function(){createjs.Tween.installPlugin(b,["startPosition"])},b.init=function(a,b,c){return c},b.step=function(){},b.tween=function(b,c,d,e,f,g,h,i){return b.target instanceof a?1==g?f[c]:e[c]:d}}(),this.createjs=this.createjs||{},function(){"use strict";function a(){throw"SpriteSheetUtils cannot be instantiated"}var b=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");b.getContext&&(a._workingCanvas=b,a._workingContext=b.getContext("2d"),b.width=b.height=1),a.addFlippedFrames=function(b,c,d,e){if(c||d||e){var f=0;c&&a._flip(b,++f,!0,!1),d&&a._flip(b,++f,!1,!0),e&&a._flip(b,++f,!0,!0)}},a.extractFrame=function(b,c){isNaN(c)&&(c=b.getAnimation(c).frames[0]);var d=b.getFrame(c);if(!d)return null;var e=d.rect,f=a._workingCanvas;f.width=e.width,f.height=e.height,a._workingContext.drawImage(d.image,e.x,e.y,e.width,e.height,0,0,e.width,e.height);var g=document.createElement("img");return g.src=f.toDataURL("image/png"),g},a.mergeAlpha=function(a,b,c){c||(c=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas")),c.width=Math.max(b.width,a.width),c.height=Math.max(b.height,a.height);var d=c.getContext("2d");return d.save(),d.drawImage(a,0,0),d.globalCompositeOperation="destination-in",d.drawImage(b,0,0),d.restore(),c},a._flip=function(b,c,d,e){for(var f=b._images,g=a._workingCanvas,h=a._workingContext,i=f.length/c,j=0;jthis.maxHeight)throw a.ERR_DIMENSIONS;for(var e=0,f=0,g=0;d.length;){var h=this._fillRow(d,e,g,c,b);if(h.w>f&&(f=h.w),e+=h.h,!h.h||!d.length){var i=createjs.createCanvas?createjs.createCanvas():document.createElement("canvas");i.width=this._getSize(f,this.maxWidth),i.height=this._getSize(e,this.maxHeight),this._data.images[g]=i,h.h||(f=e=0,g++)}}},b._setupMovieClipFrame=function(a,b){var c=a.actionsEnabled;a.actionsEnabled=!1,a.gotoAndStop(b.i),a.actionsEnabled=c,b.f&&b.f(a,b.d,b.i)},b._getSize=function(a,b){for(var c=4;Math.pow(2,++c)=0;l--){var m=b[l],n=this._scale*m.scale,o=m.sourceRect,p=m.source,q=Math.floor(n*o.x-f),r=Math.floor(n*o.y-f),s=Math.ceil(n*o.height+2*f),t=Math.ceil(n*o.width+2*f);if(t>g)throw a.ERR_DIMENSIONS;s>i||j+t>g||(m.img=d,m.rect=new createjs.Rectangle(j,c,t,s),k=k||s,b.splice(l,1),e[m.index]=[j,c,t,s,d,Math.round(-q+n*p.regX-f),Math.round(-r+n*p.regY-f)],j+=t)}return{w:j,h:k}},b._endBuild=function(){this.spriteSheet=new createjs.SpriteSheet(this._data),this._data=null,this.progress=1,this.dispatchEvent("complete")},b._run=function(){for(var a=50*Math.max(.01,Math.min(.99,this.timeSlice||.3)),b=(new Date).getTime()+a,c=!1;b>(new Date).getTime();)if(!this._drawNext()){c=!0;break}if(c)this._endBuild();else{var d=this;this._timerID=setTimeout(function(){d._run()},50-a)}var e=this.progress=this._index/this._frames.length;if(this.hasEventListener("progress")){var f=new createjs.Event("progress");f.progress=e,this.dispatchEvent(f)}},b._drawNext=function(){var a=this._frames[this._index],b=a.scale*this._scale,c=a.rect,d=a.sourceRect,e=this._data.images[a.img],f=e.getContext("2d");return a.funct&&a.funct(a.source,a.data),f.save(),f.beginPath(),f.rect(c.x,c.y,c.width,c.height),f.clip(),f.translate(Math.ceil(c.x-d.x*b),Math.ceil(c.y-d.y*b)),f.scale(b,b),a.source.draw(f),f.restore(),++this._index>1;if(isNaN(c)||c<0)return!1;var d=this.blurY>>1;if(isNaN(d)||d<0)return!1;if(0==c&&0==d)return!1;var e=this.quality;(isNaN(e)||e<1)&&(e=1),e|=0,e>3&&(e=3),e<1&&(e=1);var f=b.data,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=c+c+1|0,w=d+d+1|0,x=0|b.width,y=0|b.height,z=x-1|0,A=y-1|0,B=c+1|0,C=d+1|0,D={r:0,b:0,g:0,a:0},E=D;for(i=1;i0;){m=l=0;var M=I,N=J;for(h=y;--h>-1;){for(n=B*(r=f[0|l]),o=B*(s=f[l+1|0]),p=B*(t=f[l+2|0]),q=B*(u=f[l+3|0]),E=D,i=B;--i>-1;)E.r=r,E.g=s,E.b=t,E.a=u,E=E.n;for(i=1;i>>N,f[l++]=o*M>>>N,f[l++]=p*M>>>N,f[l++]=q*M>>>N,j=m+((j=g+c+1)0)for(h=0;h>>N,u>0?(f[j]=n*M>>>N,f[j+1]=o*M>>>N,f[j+2]=p*M>>>N):f[j]=f[j+1]=f[j+2]=0,j=g+((j=h+C)>>N,u>0?(u=255/u,f[j]=(n*M>>>N)*u,f[j+1]=(o*M>>>N)*u,f[j+2]=(p*M>>>N)*u):f[j]=f[j+1]=f[j+2]=0,j=g+((j=h+C)0?3*a/100:a/100),c=.3086,d=.6094,e=.082;return this._multiplyMatrix([c*(1-b)+b,d*(1-b),e*(1-b),0,0,c*(1-b),d*(1-b)+b,e*(1-b),0,0,c*(1-b),d*(1-b),e*(1-b)+b,0,0,0,0,0,1,0,0,0,0,0,1]),this},b.adjustHue=function(a){if(0==a||isNaN(a))return this;a=this._cleanValue(a,180)/180*Math.PI;var b=Math.cos(a),c=Math.sin(a),d=.213,e=.715,f=.072;return this._multiplyMatrix([d+b*(1-d)+c*-d,e+b*-e+c*-e,f+b*-f+c*(1-f),0,0,d+b*-d+.143*c,e+b*(1-e)+.14*c,f+b*-f+-.283*c,0,0,d+b*-d+c*-(1-d),e+b*-e+c*e,f+b*(1-f)+c*f,0,0,0,0,0,1,0,0,0,0,0,1]),this},b.concat=function(b){return b=this._fixMatrix(b),b.length!=a.LENGTH?this:(this._multiplyMatrix(b),this)},b.clone=function(){return(new a).copy(this)},b.toArray=function(){for(var b=[],c=0,d=a.LENGTH;ca.LENGTH&&(b=b.slice(0,a.LENGTH)),b},createjs.ColorMatrix=a}(),this.createjs=this.createjs||{},function(){"use strict";function a(a){this.matrix=a}var b=createjs.extend(a,createjs.Filter);b.toString=function(){return"[ColorMatrixFilter]"},b.clone=function(){return new a(this.matrix)},b._applyFilter=function(a){for(var b,c,d,e,f=a.data,g=f.length,h=this.matrix,i=h[0],j=h[1],k=h[2],l=h[3],m=h[4],n=h[5],o=h[6],p=h[7],q=h[8],r=h[9],s=h[10],t=h[11],u=h[12],v=h[13],w=h[14],x=h[15],y=h[16],z=h[17],A=h[18],B=h[19],C=0;C0||window.navigator.pointerEnabled&&window.navigator.maxTouchPoints>0)},a.enable=function(b,c,d){return!!(b&&b.canvas&&a.isSupported())&&(!!b.__touch||(b.__touch={pointers:{},multitouch:!c,preventDefault:!d,count:0},"ontouchstart"in window?a._IOS_enable(b):(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&a._IE_enable(b),!0))},a.disable=function(b){b&&("ontouchstart"in window?a._IOS_disable(b):(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&a._IE_disable(b),delete b.__touch)},a._IOS_enable=function(b){var c=b.canvas,d=b.__touch.f=function(c){a._IOS_handleEvent(b,c)};c.addEventListener("touchstart",d,!1),c.addEventListener("touchmove",d,!1),c.addEventListener("touchend",d,!1),c.addEventListener("touchcancel",d,!1)},a._IOS_disable=function(a){var b=a.canvas;if(b){var c=a.__touch.f;b.removeEventListener("touchstart",c,!1),b.removeEventListener("touchmove",c,!1),b.removeEventListener("touchend",c,!1),b.removeEventListener("touchcancel",c,!1)}},a._IOS_handleEvent=function(a,b){if(a){a.__touch.preventDefault&&b.preventDefault&&b.preventDefault();for(var c=b.changedTouches,d=b.type,e=0,f=c.length;e1?this.addChildAt.apply(this,Array.prototype.slice.call(arguments).concat([this.children.length])):this.addChildAt(a,this.children.length)},b.addChildAt=function(a,b){var c=arguments.length,d=arguments[c-1];if(0>d||d>this.children.length)return arguments[c-2];if(c>2){for(var e=0;c-1>e;e++)this.addChildAt(arguments[e],d+e);return arguments[c-2]}if(!(a._spritestage_compatibility>=1))return console&&console.log("Error: You can only add children of type SpriteContainer, Sprite, BitmapText, or DOMElement ["+a.toString()+"]"),a;if(a._spritestage_compatibility<=4){var f=a.spriteSheet;if(!f||!f._images||f._images.length>1||this.spriteSheet&&this.spriteSheet!==f)return console&&console.log("Error: A child's spriteSheet must be equal to its parent spriteSheet and only use one image. ["+a.toString()+"]"),a;this.spriteSheet=f}return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.splice(b,0,a),a},b.toString=function(){return"[SpriteContainer (name="+this.name+")]"},createjs.SpriteContainer=createjs.promote(a,"Container")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c){this.Stage_constructor(a),this._preserveDrawingBuffer=b||!1,this._antialias=c||!1,this._viewportWidth=0,this._viewportHeight=0,this._projectionMatrix=null,this._webGLContext=null,this._webGLErrorDetected=!1,this._clearColor=null,this._maxTexturesPerDraw=1,this._maxBoxesPointsPerDraw=null,this._maxBoxesPerDraw=null,this._maxIndicesPerDraw=null,this._shaderProgram=null,this._vertices=null,this._verticesBuffer=null,this._indices=null,this._indicesBuffer=null,this._currentBoxIndex=-1,this._drawTexture=null,this._initializeWebGL()}[createjs.SpriteContainer,createjs.Sprite,createjs.BitmapText,createjs.Bitmap,createjs.DOMElement].forEach(function(a,b){a.prototype._spritestage_compatibility=b+1});var b=createjs.extend(a,createjs.Stage);a.NUM_VERTEX_PROPERTIES=5,a.POINTS_PER_BOX=4,a.NUM_VERTEX_PROPERTIES_PER_BOX=a.POINTS_PER_BOX*a.NUM_VERTEX_PROPERTIES,a.INDICES_PER_BOX=6,a.MAX_INDEX_SIZE=Math.pow(2,16),a.MAX_BOXES_POINTS_INCREMENT=a.MAX_INDEX_SIZE/4,b._get_isWebGL=function(){return!!this._webGLContext};try{Object.defineProperties(b,{isWebGL:{get:b._get_isWebGL}})}catch(c){}b.addChild=function(a){return null==a?a:arguments.length>1?this.addChildAt.apply(this,Array.prototype.slice.call(arguments).concat([this.children.length])):this.addChildAt(a,this.children.length)},b.addChildAt=function(a,b){var c=arguments.length,d=arguments[c-1];if(0>d||d>this.children.length)return arguments[c-2];if(c>2){for(var e=0;c-1>e;e++)this.addChildAt(arguments[e],d+e);return arguments[c-2]}return a._spritestage_compatibility>=1?!a.image&&!a.spriteSheet&&a._spritestage_compatibility<=4?(console&&console.log("Error: You can only add children that have an image or spriteSheet defined on them. ["+a.toString()+"]"),a):(a.parent&&a.parent.removeChild(a),a.parent=this,this.children.splice(b,0,a),a):(console&&console.log("Error: You can only add children of type SpriteContainer, Sprite, Bitmap, BitmapText, or DOMElement. ["+a.toString()+"]"),a)},b.update=function(a){if(this.canvas){this.tickOnUpdate&&this.tick(a),this.dispatchEvent("drawstart"),this.autoClear&&this.clear();var b=this._setWebGLContext();b?this.draw(b,!1):(b=this.canvas.getContext("2d"),b.save(),this.updateContext(b),this.draw(b,!1),b.restore()),this.dispatchEvent("drawend")}},b.clear=function(){if(this.canvas){var a=this._setWebGLContext();a?a.clear(a.COLOR_BUFFER_BIT):(a=this.canvas.getContext("2d"),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,this.canvas.width+1,this.canvas.height+1))}},b.draw=function(a,b){return"undefined"!=typeof WebGLRenderingContext&&(a===this._webGLContext||a instanceof WebGLRenderingContext)?(this._drawWebGLKids(this.children,a),!0):this.Stage_draw(a,b)},b.updateViewport=function(a,b){this._viewportWidth=a,this._viewportHeight=b,this._webGLContext&&(this._webGLContext.viewport(0,0,this._viewportWidth,this._viewportHeight),this._projectionMatrix||(this._projectionMatrix=new Float32Array([0,0,0,0,0,1,-1,1,1])),this._projectionMatrix[0]=2/a,this._projectionMatrix[4]=-2/b)},b.clearImageTexture=function(a){a.__easeljs_texture=null},b.toString=function(){return"[SpriteStage (name="+this.name+")]"},b._initializeWebGL=function(){this._clearColor={r:0,g:0,b:0,a:0},this._setWebGLContext()},b._setWebGLContext=function(){return this.canvas?this._webGLContext&&this._webGLContext.canvas===this.canvas||this._initializeWebGLContext():this._webGLContext=null,this._webGLContext},b._initializeWebGLContext=function(){var a={depth:!1,alpha:!0,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias,premultipliedAlpha:!0},b=this._webGLContext=this.canvas.getContext("webgl",a)||this.canvas.getContext("experimental-webgl",a);if(b){if(this._maxTexturesPerDraw=1,this._setClearColor(this._clearColor.r,this._clearColor.g,this._clearColor.b,this._clearColor.a),b.enable(b.BLEND),b.blendFuncSeparate(b.SRC_ALPHA,b.ONE_MINUS_SRC_ALPHA,b.ONE,b.ONE_MINUS_SRC_ALPHA),b.pixelStorei(b.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),this._createShaderProgram(b),this._webGLErrorDetected)return void(this._webGLContext=null);this._createBuffers(b),this.updateViewport(this._viewportWidth||this.canvas.width||0,this._viewportHeight||this.canvas.height||0)}},b._setClearColor=function(a,b,c,d){this._clearColor.r=a,this._clearColor.g=b,this._clearColor.b=c,this._clearColor.a=d,this._webGLContext&&this._webGLContext.clearColor(a,b,c,d)},b._createShaderProgram=function(a){var b=this._createShader(a,a.FRAGMENT_SHADER,"precision mediump float;uniform sampler2D uSampler0;varying vec3 vTextureCoord;void main(void) {vec4 color = texture2D(uSampler0, vTextureCoord.st);gl_FragColor = vec4(color.rgb, color.a * vTextureCoord.z);}"),c=this._createShader(a,a.VERTEX_SHADER,"attribute vec2 aVertexPosition;attribute vec3 aTextureCoord;uniform mat3 uPMatrix;varying vec3 vTextureCoord;void main(void) {vTextureCoord = aTextureCoord;gl_Position = vec4((uPMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);}");if(!this._webGLErrorDetected&&b&&c){var d=a.createProgram();if(a.attachShader(d,b),a.attachShader(d,c),a.linkProgram(d),!a.getProgramParameter(d,a.LINK_STATUS))return void(this._webGLErrorDetected=!0);d.vertexPositionAttribute=a.getAttribLocation(d,"aVertexPosition"),d.textureCoordAttribute=a.getAttribLocation(d,"aTextureCoord"),d.sampler0uniform=a.getUniformLocation(d,"uSampler0"),a.enableVertexAttribArray(d.vertexPositionAttribute),a.enableVertexAttribArray(d.textureCoordAttribute),d.pMatrixUniform=a.getUniformLocation(d,"uPMatrix"),a.useProgram(d),this._shaderProgram=d}},b._createShader=function(a,b,c){var d=a.createShader(b);return a.shaderSource(d,c),a.compileShader(d),a.getShaderParameter(d,a.COMPILE_STATUS)?d:(this._webGLErrorDetected=!0,null)},b._createBuffers=function(b){this._verticesBuffer=b.createBuffer(),b.bindBuffer(b.ARRAY_BUFFER,this._verticesBuffer);var c=4*a.NUM_VERTEX_PROPERTIES;b.vertexAttribPointer(this._shaderProgram.vertexPositionAttribute,2,b.FLOAT,b.FALSE,c,0),b.vertexAttribPointer(this._shaderProgram.textureCoordAttribute,3,b.FLOAT,b.FALSE,c,8),this._indicesBuffer=b.createBuffer(),this._setMaxBoxesPoints(b,a.MAX_BOXES_POINTS_INCREMENT)},b._setMaxBoxesPoints=function(b,c){this._maxBoxesPointsPerDraw=c,this._maxBoxesPerDraw=this._maxBoxesPointsPerDraw/a.POINTS_PER_BOX|0,this._maxIndicesPerDraw=this._maxBoxesPerDraw*a.INDICES_PER_BOX,b.bindBuffer(b.ARRAY_BUFFER,this._verticesBuffer),this._vertices=new Float32Array(this._maxBoxesPerDraw*a.NUM_VERTEX_PROPERTIES_PER_BOX),b.bufferData(b.ARRAY_BUFFER,this._vertices,b.DYNAMIC_DRAW),this._indices=new Uint16Array(this._maxIndicesPerDraw);for(var d=0,e=this._indices.length;e>d;d+=a.INDICES_PER_BOX){var f=d*a.POINTS_PER_BOX/a.INDICES_PER_BOX;this._indices[d]=f,this._indices[d+1]=f+1,this._indices[d+2]=f+2,this._indices[d+3]=f,this._indices[d+4]=f+2,this._indices[d+5]=f+3}b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,this._indicesBuffer),b.bufferData(b.ELEMENT_ARRAY_BUFFER,this._indices,b.STATIC_DRAW)},b._setupImageTexture=function(a,b){if(b&&(b.naturalWidth||b.getContext||b.readyState>=2)){var c=b.__easeljs_texture;return c||(c=b.__easeljs_texture=a.createTexture(),a.bindTexture(a.TEXTURE_2D,c),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,b),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE)),c}},b._drawWebGLKids=function(b,c,d){for(var e,f,g=this.snapToPixelEnabled,h=null,i=0,j=0,k=0,l=0,m=this._vertices,n=a.NUM_VERTEX_PROPERTIES_PER_BOX,o=a.MAX_INDEX_SIZE,p=this._maxBoxesPerDraw-1,q=0,r=b.length;r>q;q++)if(e=b[q],e.isVisible()){var h=e.image||e.spriteSheet&&e.spriteSheet._images[0],s=h.__easeljs_texture;if(s||(s=this._setupImageTexture(c,h))){f=e._props.matrix,f=(d?f.copy(d):f.identity()).appendTransform(e.x,e.y,e.scaleX,e.scaleY,e.rotation,e.skewX,e.skewY,e.regX,e.regY);var t=0,u=1,v=0,w=1;if(4===e._spritestage_compatibility)i=0,j=0,k=h.width,l=h.height;else if(2===e._spritestage_compatibility){var x=e.spriteSheet.getFrame(e.currentFrame),y=x.rect;i=-x.regX,j=-x.regY,k=i+y.width,l=j+y.height,t=y.x/h.width,v=y.y/h.height,u=t+y.width/h.width,w=v+y.height/h.height}else h=null,3===e._spritestage_compatibility&&e._updateText();if(!d&&e._spritestage_compatibility<=4&&s!==this._drawTexture&&(this._drawToGPU(c),this._drawTexture=s),null!==h){var z=++this._currentBoxIndex*n,A=f.a,B=f.b,C=f.c,D=f.d,E=f.tx,F=f.ty;g&&e.snapToPixel&&(E=E+(0>E?-.5:.5)|0,F=F+(0>F?-.5:.5)|0),m[z]=i*A+j*C+E,m[z+1]=i*B+j*D+F,m[z+5]=i*A+l*C+E,m[z+6]=i*B+l*D+F,m[z+10]=k*A+l*C+E,m[z+11]=k*B+l*D+F,m[z+15]=k*A+j*C+E,m[z+16]=k*B+j*D+F,m[z+2]=m[z+7]=t,m[z+12]=m[z+17]=u,m[z+3]=m[z+18]=v,m[z+8]=m[z+13]=w,m[z+4]=m[z+9]=m[z+14]=m[z+19]=e.alpha,this._currentBoxIndex===p&&(this._drawToGPU(c),this._drawTexture=s,this._maxBoxesPointsPerDraw1?this.addChildAt.apply(this,Array.prototype.slice.call(arguments).concat([this.children.length])):this.addChildAt(a,this.children.length)},b.addChildAt=function(a,b){var c=arguments.length,d=arguments[c-1];if(d<0||d>this.children.length)return arguments[c-2];if(c>2){for(var e=0;e=1))return console&&console.log("Error: You can only add children of type SpriteContainer, Sprite, BitmapText, or DOMElement ["+a.toString()+"]"),a;if(a._spritestage_compatibility<=4){var f=a.spriteSheet;if(!f||!f._images||f._images.length>1||this.spriteSheet&&this.spriteSheet!==f)return console&&console.log("Error: A child's spriteSheet must be equal to its parent spriteSheet and only use one image. ["+a.toString()+"]"),a;this.spriteSheet=f}return a.parent&&a.parent.removeChild(a),a.parent=this,this.children.splice(b,0,a),a},b.toString=function(){return"[SpriteContainer (name="+this.name+")]"},createjs.SpriteContainer=createjs.promote(a,"Container")}(),this.createjs=this.createjs||{},function(){"use strict";function a(a,b,c){this.Stage_constructor(a),this._preserveDrawingBuffer=b||!1,this._antialias=c||!1,this._viewportWidth=0,this._viewportHeight=0,this._projectionMatrix=null,this._webGLContext=null,this._webGLErrorDetected=!1,this._clearColor=null,this._maxTexturesPerDraw=1,this._maxBoxesPointsPerDraw=null,this._maxBoxesPerDraw=null,this._maxIndicesPerDraw=null,this._shaderProgram=null,this._vertices=null,this._verticesBuffer=null,this._indices=null,this._indicesBuffer=null,this._currentBoxIndex=-1,this._drawTexture=null,this._initializeWebGL()}[createjs.SpriteContainer,createjs.Sprite,createjs.BitmapText,createjs.Bitmap,createjs.DOMElement].forEach(function(a,b){a.prototype._spritestage_compatibility=b+1});var b=createjs.extend(a,createjs.Stage);a.NUM_VERTEX_PROPERTIES=5,a.POINTS_PER_BOX=4,a.NUM_VERTEX_PROPERTIES_PER_BOX=a.POINTS_PER_BOX*a.NUM_VERTEX_PROPERTIES,a.INDICES_PER_BOX=6,a.MAX_INDEX_SIZE=Math.pow(2,16),a.MAX_BOXES_POINTS_INCREMENT=a.MAX_INDEX_SIZE/4,b._get_isWebGL=function(){return!!this._webGLContext};try{Object.defineProperties(b,{isWebGL:{get:b._get_isWebGL}})}catch(a){}b.addChild=function(a){return null==a?a:arguments.length>1?this.addChildAt.apply(this,Array.prototype.slice.call(arguments).concat([this.children.length])):this.addChildAt(a,this.children.length)},b.addChildAt=function(a,b){var c=arguments.length,d=arguments[c-1];if(d<0||d>this.children.length)return arguments[c-2];if(c>2){for(var e=0;e=1?!a.image&&!a.spriteSheet&&a._spritestage_compatibility<=4?(console&&console.log("Error: You can only add children that have an image or spriteSheet defined on them. ["+a.toString()+"]"),a):(a.parent&&a.parent.removeChild(a),a.parent=this,this.children.splice(b,0,a),a):(console&&console.log("Error: You can only add children of type SpriteContainer, Sprite, Bitmap, BitmapText, or DOMElement. ["+a.toString()+"]"),a)},b.update=function(a){if(this.canvas){this.tickOnUpdate&&this.tick(a),this.dispatchEvent("drawstart"),this.autoClear&&this.clear();var b=this._setWebGLContext();b?this.draw(b,!1):(b=this.canvas.getContext("2d"),b.save(),this.updateContext(b),this.draw(b,!1),b.restore()),this.dispatchEvent("drawend")}},b.clear=function(){if(this.canvas){var a=this._setWebGLContext();a?a.clear(a.COLOR_BUFFER_BIT):(a=this.canvas.getContext("2d"),a.setTransform(1,0,0,1,0,0),a.clearRect(0,0,this.canvas.width+1,this.canvas.height+1))}},b.draw=function(a,b){return"undefined"!=typeof WebGLRenderingContext&&(a===this._webGLContext||a instanceof WebGLRenderingContext)?(this._drawWebGLKids(this.children,a),!0):this.Stage_draw(a,b)},b.updateViewport=function(a,b){this._viewportWidth=a,this._viewportHeight=b,this._webGLContext&&(this._webGLContext.viewport(0,0,this._viewportWidth,this._viewportHeight),this._projectionMatrix||(this._projectionMatrix=new Float32Array([0,0,0,0,0,1,-1,1,1])),this._projectionMatrix[0]=2/a,this._projectionMatrix[4]=-2/b)},b.clearImageTexture=function(a){a.__easeljs_texture=null},b.toString=function(){return"[SpriteStage (name="+this.name+")]"},b._initializeWebGL=function(){this._clearColor={r:0,g:0,b:0,a:0},this._setWebGLContext()},b._setWebGLContext=function(){return this.canvas?this._webGLContext&&this._webGLContext.canvas===this.canvas||this._initializeWebGLContext():this._webGLContext=null,this._webGLContext},b._initializeWebGLContext=function(){var a={depth:!1,alpha:!0,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias,premultipliedAlpha:!0},b=this._webGLContext=this.canvas.getContext("webgl",a)||this.canvas.getContext("experimental-webgl",a);if(b){if(this._maxTexturesPerDraw=1,this._setClearColor(this._clearColor.r,this._clearColor.g,this._clearColor.b,this._clearColor.a),b.enable(b.BLEND),b.blendFuncSeparate(b.SRC_ALPHA,b.ONE_MINUS_SRC_ALPHA,b.ONE,b.ONE_MINUS_SRC_ALPHA),b.pixelStorei(b.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),this._createShaderProgram(b),this._webGLErrorDetected)return void(this._webGLContext=null);this._createBuffers(b),this.updateViewport(this._viewportWidth||this.canvas.width||0,this._viewportHeight||this.canvas.height||0)}},b._setClearColor=function(a,b,c,d){this._clearColor.r=a,this._clearColor.g=b,this._clearColor.b=c,this._clearColor.a=d,this._webGLContext&&this._webGLContext.clearColor(a,b,c,d)},b._createShaderProgram=function(a){var b=this._createShader(a,a.FRAGMENT_SHADER,"precision mediump float;uniform sampler2D uSampler0;varying vec3 vTextureCoord;void main(void) {vec4 color = texture2D(uSampler0, vTextureCoord.st);gl_FragColor = vec4(color.rgb, color.a * vTextureCoord.z);}"),c=this._createShader(a,a.VERTEX_SHADER,"attribute vec2 aVertexPosition;attribute vec3 aTextureCoord;uniform mat3 uPMatrix;varying vec3 vTextureCoord;void main(void) {vTextureCoord = aTextureCoord;gl_Position = vec4((uPMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);}");if(!this._webGLErrorDetected&&b&&c){var d=a.createProgram();if(a.attachShader(d,b),a.attachShader(d,c),a.linkProgram(d),!a.getProgramParameter(d,a.LINK_STATUS))return void(this._webGLErrorDetected=!0);d.vertexPositionAttribute=a.getAttribLocation(d,"aVertexPosition"),d.textureCoordAttribute=a.getAttribLocation(d,"aTextureCoord"),d.sampler0uniform=a.getUniformLocation(d,"uSampler0"),a.enableVertexAttribArray(d.vertexPositionAttribute),a.enableVertexAttribArray(d.textureCoordAttribute),d.pMatrixUniform=a.getUniformLocation(d,"uPMatrix"),a.useProgram(d),this._shaderProgram=d}},b._createShader=function(a,b,c){var d=a.createShader(b);return a.shaderSource(d,c),a.compileShader(d),a.getShaderParameter(d,a.COMPILE_STATUS)?d:(this._webGLErrorDetected=!0,null)},b._createBuffers=function(b){this._verticesBuffer=b.createBuffer(),b.bindBuffer(b.ARRAY_BUFFER,this._verticesBuffer);var c=4*a.NUM_VERTEX_PROPERTIES;b.vertexAttribPointer(this._shaderProgram.vertexPositionAttribute,2,b.FLOAT,b.FALSE,c,0),b.vertexAttribPointer(this._shaderProgram.textureCoordAttribute,3,b.FLOAT,b.FALSE,c,8),this._indicesBuffer=b.createBuffer(),this._setMaxBoxesPoints(b,a.MAX_BOXES_POINTS_INCREMENT)},b._setMaxBoxesPoints=function(b,c){this._maxBoxesPointsPerDraw=c,this._maxBoxesPerDraw=this._maxBoxesPointsPerDraw/a.POINTS_PER_BOX|0,this._maxIndicesPerDraw=this._maxBoxesPerDraw*a.INDICES_PER_BOX,b.bindBuffer(b.ARRAY_BUFFER,this._verticesBuffer),this._vertices=new Float32Array(this._maxBoxesPerDraw*a.NUM_VERTEX_PROPERTIES_PER_BOX),b.bufferData(b.ARRAY_BUFFER,this._vertices,b.DYNAMIC_DRAW),this._indices=new Uint16Array(this._maxIndicesPerDraw);for(var d=0,e=this._indices.length;d=2)){var c=b.__easeljs_texture;return c||(c=b.__easeljs_texture=a.createTexture(),a.bindTexture(a.TEXTURE_2D,c),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,b),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE)),c}},b._drawWebGLKids=function(b,c,d){for(var e,f,g=this.snapToPixelEnabled,h=null,i=0,j=0,k=0,l=0,m=this._vertices,n=a.NUM_VERTEX_PROPERTIES_PER_BOX,o=a.MAX_INDEX_SIZE,p=this._maxBoxesPerDraw-1,q=0,r=b.length;qlt {{#crossLink "Graphics/lineTo"}}{{/crossLink}} * a/at{{#crossLink "Graphics/arc"}}{{/crossLink}} / {{#crossLink "Graphics/arcTo"}}{{/crossLink}} * bt{{#crossLink "Graphics/bezierCurveTo"}}{{/crossLink}} - * qt{{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} (also curveTo) + * ea{{#crossLink "Graphics/ellipticalArc"}}{{/crossLink}} * r{{#crossLink "Graphics/rect"}}{{/crossLink}} - * cp{{#crossLink "Graphics/closePath"}}{{/crossLink}} + * qt{{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} (also curveTo) * c{{#crossLink "Graphics/clear"}}{{/crossLink}} - * f{{#crossLink "Graphics/beginFill"}}{{/crossLink}} + * cp{{#crossLink "Graphics/closePath"}}{{/crossLink}} * lf{{#crossLink "Graphics/beginLinearGradientFill"}}{{/crossLink}} - * rf{{#crossLink "Graphics/beginRadialGradientFill"}}{{/crossLink}} + * f{{#crossLink "Graphics/beginFill"}}{{/crossLink}} * bf{{#crossLink "Graphics/beginBitmapFill"}}{{/crossLink}} - * ef{{#crossLink "Graphics/endFill"}}{{/crossLink}} + * rf{{#crossLink "Graphics/beginRadialGradientFill"}}{{/crossLink}} * ss / sd{{#crossLink "Graphics/setStrokeStyle"}}{{/crossLink}} / {{#crossLink "Graphics/setStrokeDash"}}{{/crossLink}} - * s{{#crossLink "Graphics/beginStroke"}}{{/crossLink}} + * ef{{#crossLink "Graphics/endFill"}}{{/crossLink}} * ls{{#crossLink "Graphics/beginLinearGradientStroke"}}{{/crossLink}} - * rs{{#crossLink "Graphics/beginRadialGradientStroke"}}{{/crossLink}} + * s{{#crossLink "Graphics/beginStroke"}}{{/crossLink}} * bs{{#crossLink "Graphics/beginBitmapStroke"}}{{/crossLink}} - * es{{#crossLink "Graphics/endStroke"}}{{/crossLink}} + * rs{{#crossLink "Graphics/beginRadialGradientStroke"}}{{/crossLink}} * dr{{#crossLink "Graphics/drawRect"}}{{/crossLink}} - * rr{{#crossLink "Graphics/drawRoundRect"}}{{/crossLink}} + * es{{#crossLink "Graphics/endStroke"}}{{/crossLink}} * rc{{#crossLink "Graphics/drawRoundRectComplex"}}{{/crossLink}} - * dc{{#crossLink "Graphics/drawCircle"}}{{/crossLink}} + * rr{{#crossLink "Graphics/drawRoundRect"}}{{/crossLink}} * de{{#crossLink "Graphics/drawEllipse"}}{{/crossLink}} - * dp{{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} + * dc{{#crossLink "Graphics/drawCircle"}}{{/crossLink}} * p{{#crossLink "Graphics/decodePath"}}{{/crossLink}} + * dp{{#crossLink "Graphics/drawPolyStar"}}{{/crossLink}} * * * Here is the above example, using the tiny API instead. @@ -533,6 +534,27 @@ this.createjs = this.createjs||{}; return this.append(new G.Arc(x, y, radius, startAngle, endAngle, anticlockwise)); }; + /** + * Draws an elliptical arc defined by the radii rx and ry, startAngle and endAngle arguments, centered at the position (x, y). + * + * A tiny API method "ea" also exists. + * @method ellipticalArc + * @param {Number} x center X + * @param {Number} y center Y + * @param {Number} rx horizontal radius + * @param {Number} ry vertical radius + * @param {Number} startAngle Measured in radians. + * @param {Number} endAngle Measured in radians. + * @param {Boolean} anticlockwise if true, clockwise if false + * @param {String} closure omit for no closure (just an arc), 'radii' (makes a sector), 'chord' (makes a segment) + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @chainable + **/ + p.ellipticalArc = function(x, y, rx, ry, startAngle, endAngle, anticlockwise, closure) { + return this.append(new G.EllipticalArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, closure)); + } + + /** * Draws a quadratic curve from the current drawing point to (x, y) using the control point (cpx, cpy). For detailed * information, read the @@ -1259,6 +1281,23 @@ this.createjs = this.createjs||{}; **/ p.a = p.arc; + /** + * Shortcut to ellipticalArc. + * @method ea + * @param {Number} x + * @param {Number} y + * @param {Number} rx + * @param {Number} ry + * @param {Number} startAngle Measured in radians. + * @param {Number} endAngle Measured in radians. + * @param {Boolean} anticlockwise + * @param {String} closure omit for no closure (just an arc), 'radii' (makes a sector), 'chord' (makes a segment) + * @return {Graphics} The Graphics instance the method is called on (useful for chaining calls.) + * @protected + * @chainable + **/ + p.ea = p.ellipticalArc; + /** * Shortcut to rect. * @method r @@ -1769,6 +1808,300 @@ this.createjs = this.createjs||{}; this.anticlockwise = !!anticlockwise; }).prototype.exec = function(ctx) { ctx.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle, this.anticlockwise); }; + /** + * Graphics command object. See {{#crossLink "Graphics"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. + * @class EllipticalArc + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} rx + * @param {Number} ry + * @param {Number} startAngle + * @param {Number} endAngle + * @param {Boolean} anticlockwise + * @param {String} closure + **/ + /** + * @property x + * @type Number + */ + /** + * @property y + * @type Number + */ + /** + * @property rx + * @type Number + */ + /** + * @property ry + * @Type Number + /** + * @property startAngle + * @type Number + */ + /** + * @property endAngle + * @type Number + */ + /** + * @property anticlockwise + * @type Boolean + */ + /** + * @property closure + * @type String + */ + (G.EllipticalArc = function(x, y, rx, ry, startAngle, endAngle, anticlockwise, closure) { + this.x = x; + this.y = y; + this.rx = rx; + this.ry = ry; + this.anticlockwise = !!anticlockwise; + this.closure = closure; + + // Map negative angles into positive range + if (startAngle < 0 || endAngle < 0) { + if (startAngle < -2 * Math.PI) { + var s = startAngle / (2 * Math.PI); + startAngle = (s + Math.floor(Math.abs(s))) * 2 * Math.PI + 2 * Math.PI; + } + else if (startAngle < 0) { + startAngle += 2 * Math.PI; + } + + if (endAngle < -2 * Math.PI) { + var e = endAngle / (2 * Math.PI); + endAngle = (e + Math.floor(Math.abs(e))) * 2 * Math.PI + 2 * Math.PI; + } + else if (endAngle < 0) { + endAngle += 2 * Math.PI; + } + } + + // Normalize the angles + if (startAngle < endAngle || equalEnough(startAngle, endAngle)) { + if (this.anticlockwise === false || equalEnough(startAngle, endAngle)) { + this.start = -endAngle; + this.end = -startAngle - 2 * Math.PI; + } + else { + this.start = -startAngle; + this.end = -endAngle; + } + } + else { + if (this.anticlockwise === true) { + this.start = -startAngle; + this.end = -endAngle - 2 * Math.PI; + } + else { + this.start = -endAngle; + this.end = -startAngle; + } + } + }).prototype.exec = function(ctx) { + // x, y - top left + // xe, ye - bottom right + // xm, ym - center + var rx = this.rx; + var ry = this.ry; + var start = this.start; + var end = this.end; + var xm = this.x; + var ym = this.y; + var closure = this.closure; + + var quadrantStart = Math.floor(2 * Math.abs(start) / Math.PI); + + // How long is the arc + var span = Math.abs(end); + + // Array of intermediate angles for + // breaking up the arc into segments <= PI/2 + var ia = [0]; + + for (var i = 1; i <= 4; i++) { + ia[i - 1] = (quadrantStart + i) * Math.PI / 2; + } + + var startPoint; + var chordMidX; + var chordMidY; + + if (closure === 'radii') { + ctx.moveTo(xm, ym); + } + else if (closure === 'chord') { + var startEA = eccentricAnomalyFromPolarAngle(start, rx, ry); + var endEA = eccentricAnomalyFromPolarAngle(end, rx, ry); + + chordMidX = xm + rx * (Math.cos(startEA) + Math.cos(endEA)) / 2; + chordMidY = ym + ry * (Math.sin(startEA) + Math.sin(endEA)) / 2; + + ctx.moveTo(chordMidX, chordMidY); + } + + if (span <= ia[0]) // 1 segment + { + startPoint = elarcseg(ctx, xm, ym, rx, ry, start, end, closure); + } + else if (span <= ia[1]) // 2 segments + { + startPoint = elarcseg(ctx, xm, ym, rx, ry, start, -ia[0], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[0], end, closure); + } + else if (span <= ia[2]) // 3 segments + { + startPoint = elarcseg(ctx, xm, ym, rx, ry, start, -ia[0], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[0], -ia[1], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[1], end, closure); + } + else if (span <= ia[3]) // 4 segments + { + startPoint = elarcseg(ctx, xm, ym, rx, ry, start, -ia[0], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[0], -ia[1], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[1], -ia[2], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[2], end, closure); + } + else // 5 segments + { + startPoint = elarcseg(ctx, xm, ym, rx, ry, start, -ia[0], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[0], -ia[1], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[1], -ia[2], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[2], -ia[3], closure); + elarcseg(ctx, xm, ym, rx, ry, -ia[3], end, closure); + } + + if (closure === 'radii') { + ctx.lineTo(xm, ym); + ctx.closePath(); + } + else if (closure === 'chord') { + ctx.lineTo(chordMidX, chordMidY); + + ctx.closePath(); + } + }; + + /** + * Begin support functions for elliptical arc + **/ + + // Elliptical arc segment + function elarcseg(ctx, xm, ym, rx, ry, start, end, closure) { + var startEA = eccentricAnomalyFromPolarAngle(start, rx, ry); + var endEA = eccentricAnomalyFromPolarAngle(end, rx, ry); + + // From parametric equation by L. Maisonobe + var k = -Math.sin(endEA - startEA) * (Math.sqrt(4 + 3 * Math.pow(Math.tan((endEA - startEA) / 2), 2)) - 1) / 3; + + // Starting point of the curve + var r1 = rx * ry / Math.sqrt(Math.pow(ry * Math.cos(start), 2) + Math.pow(rx * Math.sin(start), 2)); + var x1 = xm + r1 * Math.cos(start); + var y1 = ym + r1 * Math.sin(start); + + // End point of the curve + var r2 = rx * ry / Math.sqrt(Math.pow(ry * Math.cos(end), 2) + Math.pow(rx * Math.sin(end), 2)); + var x2 = xm + r2 * Math.cos(end); + var y2 = ym + r2 * Math.sin(end); + + // Control point 1 + var x3 = x1 - k * Math.sin(-startEA) * rx; + var y3 = y1 - k * Math.cos(-startEA) * ry; + + // Control point 2 + var x4 = x2 + k * Math.sin(-endEA) * rx; + var y4 = y2 + k * Math.cos(-endEA) * ry; + + if (closure === 'radii' || closure === 'chord') { + ctx.lineTo(x1, y1); + } + else { + ctx.moveTo(x1, y1); + } + + ctx.bezierCurveTo(x3, y3, x4, y4, x2, y2); + + var startPoint = { x: x1, y: y1 }; + + return startPoint; + } + + // Maps from polar angle into the angle used in ellipse + // parametric equations (this angle is called "eccentricAnomaly") + // it is the same as polar angle when the ellipse is a circle + // E = atan((rx/ry)*tan(A)) + // where A is the polar angle and E is the eccentricAnomaly angle + function eccentricAnomalyFromPolarAngle(angle, rx, ry) { + var retval; + + var cosa = Math.cos(angle); + var sina = Math.sin(angle); + + // circle or near extremeties -- polar angle and + // eccentricAnomaly are the same + if (equalEnough(rx, ry) || equalEnough(Math.abs(cosa), 0) || equalEnough(Math.abs(sina), 0)) { + return angle; + } + + var tana = rx * Math.tan(angle) / ry; + + // branches of arctan function + if (cosa > 0 && sina > 0) { + retval = Math.atan(tana); + } + else if (cosa < 0 && sina > 0) { + retval = Math.PI + Math.atan(tana); + } + else if (cosa < 0 && sina < 0) { + retval = Math.PI + Math.atan(tana); + } + else if (cosa > 0 && sina < 0) { + retval = 2 * Math.PI + Math.atan(tana); + } + + return retval; + } + + // This is just a copy of mathjs.equal, or rather mathjs.nearlyEqual + // For some reason can't use mathjs here + // But, perhaps this is better as it is self-contained and won't introduce a dependency in EaselJS on mathjs + // and also, the mathjs version is too stingy on its epsilon + function equalEnough(x, y) { + var relEpsilon = 0.001; + var absEpsilon = 2.2204460492503130808472633361816E-16; + + if (x === y) { + return true; + } + + // NaN + if (isNaN(x) || isNaN(y)) { + return false; + } + + // at this point x and y should be finite + if (isFinite(x) && isFinite(y)) { + // check numbers are very close, needed when comparing numbers near zero + var diff = Math.abs(x - y); + if (diff < absEpsilon) { + return true; + } + else { + // use relative error + return diff <= Math.max(Math.abs(x), Math.abs(y)) * relEpsilon; + } + } + + // Infinite and Number or negative Infinite and positive Infinite cases + return false; + } + + /** + * End support functions for elliptical arc + **/ + /** * Graphics command object. See {{#crossLink "Graphics/quadraticCurveTo"}}{{/crossLink}} and {{#crossLink "Graphics/append"}}{{/crossLink}} for more information. * @class QuadraticCurveTo diff --git a/tests/spec/GraphicsSpec.js b/tests/spec/GraphicsSpec.js index dd299c2cf..25de98fbd 100644 --- a/tests/spec/GraphicsSpec.js +++ b/tests/spec/GraphicsSpec.js @@ -323,5 +323,9 @@ describe("Graphics", function () { it('decodePath should equal p', function () { expect(this.g['decodePath']).toBe(this.g['p']); }); + + it ('ellipticalArc should equal ea', function () { + expect(this.g['ellipticalArc']).toBe(this.g['ea']); + }); }); });