libraries/EaselJS_docs/files/easeljs_display_SpriteSheet.js.html (view raw)
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="utf-8">
5 <link rel="stylesheet" href="../assets/css/yui-cssgrids-min.css">
6 <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
7 <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
8 <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
9 <script src="../assets/js/yui-source.js"></script>
10 <title>EaselJS v1.0.0 API Documentation : easeljs/display/SpriteSheet.js</title>
11</head>
12<body class="yui3-skin-sam">
13
14<div id="doc">
15 <div id="hd" class="yui3-g header">
16 <div class="yui3-u-3-4">
17
18 <h1><a href="http://www.createjs.com/easeljs"><img src="../assets/docs-icon-EaselJS.png" title="EaselJS"></a></h1>
19
20 </div>
21 <div class="version">
22 <em>API Documentation for: 1.0.0</em>
23 </div>
24 </div>
25 <div id="bd" class="yui3-g">
26
27 <div class="yui3-u-1-4">
28 <div id="docs-sidebar" class="sidebar apidocs">
29 <div id="api-list">
30 <h2 class="off-left">APIs</h2>
31 <div id="api-tabview" class="tabview">
32 <ul class="tabs">
33 <li><a href="#api-classes">Classes</a></li>
34 </ul>
35
36 <div id="api-tabview-filter">
37 <input type="search" id="api-filter" placeholder="Type to filter APIs">
38 </div>
39
40 <div id="api-tabview-panel">
41 <ul id="api-classes" class="apis classes">
42
43 <li><a href="../classes/AlphaMapFilter.html">AlphaMapFilter</a></li>
44
45 <li><a href="../classes/AlphaMaskFilter.html">AlphaMaskFilter</a></li>
46
47 <li><a href="../classes/Bitmap.html">Bitmap</a></li>
48
49 <li><a href="../classes/BitmapCache.html">BitmapCache</a></li>
50
51 <li><a href="../classes/BitmapText.html">BitmapText</a></li>
52
53 <li><a href="../classes/BlurFilter.html">BlurFilter</a></li>
54
55 <li><a href="../classes/ButtonHelper.html">ButtonHelper</a></li>
56
57 <li><a href="../classes/ColorFilter.html">ColorFilter</a></li>
58
59 <li><a href="../classes/ColorMatrix.html">ColorMatrix</a></li>
60
61 <li><a href="../classes/ColorMatrixFilter.html">ColorMatrixFilter</a></li>
62
63 <li><a href="../classes/Container.html">Container</a></li>
64
65 <li><a href="../classes/DisplayObject.html">DisplayObject</a></li>
66
67 <li><a href="../classes/DisplayProps.html">DisplayProps</a></li>
68
69 <li><a href="../classes/DOMElement.html">DOMElement</a></li>
70
71 <li><a href="../classes/EaselJS.html">EaselJS</a></li>
72
73 <li><a href="../classes/Event.html">Event</a></li>
74
75 <li><a href="../classes/EventDispatcher.html">EventDispatcher</a></li>
76
77 <li><a href="../classes/Filter.html">Filter</a></li>
78
79 <li><a href="../classes/Graphics.html">Graphics</a></li>
80
81 <li><a href="../classes/Graphics.Arc.html">Graphics.Arc</a></li>
82
83 <li><a href="../classes/Graphics.ArcTo.html">Graphics.ArcTo</a></li>
84
85 <li><a href="../classes/Graphics.BeginPath.html">Graphics.BeginPath</a></li>
86
87 <li><a href="../classes/Graphics.BezierCurveTo.html">Graphics.BezierCurveTo</a></li>
88
89 <li><a href="../classes/Graphics.Circle.html">Graphics.Circle</a></li>
90
91 <li><a href="../classes/Graphics.ClosePath.html">Graphics.ClosePath</a></li>
92
93 <li><a href="../classes/Graphics.Ellipse.html">Graphics.Ellipse</a></li>
94
95 <li><a href="../classes/Graphics.Fill.html">Graphics.Fill</a></li>
96
97 <li><a href="../classes/Graphics.LineTo.html">Graphics.LineTo</a></li>
98
99 <li><a href="../classes/Graphics.MoveTo.html">Graphics.MoveTo</a></li>
100
101 <li><a href="../classes/Graphics.PolyStar.html">Graphics.PolyStar</a></li>
102
103 <li><a href="../classes/Graphics.QuadraticCurveTo.html">Graphics.QuadraticCurveTo</a></li>
104
105 <li><a href="../classes/Graphics.Rect.html">Graphics.Rect</a></li>
106
107 <li><a href="../classes/Graphics.RoundRect.html">Graphics.RoundRect</a></li>
108
109 <li><a href="../classes/Graphics.Stroke.html">Graphics.Stroke</a></li>
110
111 <li><a href="../classes/Graphics.StrokeDash.html">Graphics.StrokeDash</a></li>
112
113 <li><a href="../classes/Graphics.StrokeStyle.html">Graphics.StrokeStyle</a></li>
114
115 <li><a href="../classes/Matrix2D.html">Matrix2D</a></li>
116
117 <li><a href="../classes/MouseEvent.html">MouseEvent</a></li>
118
119 <li><a href="../classes/MovieClip.html">MovieClip</a></li>
120
121 <li><a href="../classes/MovieClipPlugin.html">MovieClipPlugin</a></li>
122
123 <li><a href="../classes/Point.html">Point</a></li>
124
125 <li><a href="../classes/Rectangle.html">Rectangle</a></li>
126
127 <li><a href="../classes/Shadow.html">Shadow</a></li>
128
129 <li><a href="../classes/Shape.html">Shape</a></li>
130
131 <li><a href="../classes/Sprite.html">Sprite</a></li>
132
133 <li><a href="../classes/SpriteSheet.html">SpriteSheet</a></li>
134
135 <li><a href="../classes/SpriteSheetBuilder.html">SpriteSheetBuilder</a></li>
136
137 <li><a href="../classes/SpriteSheetUtils.html">SpriteSheetUtils</a></li>
138
139 <li><a href="../classes/Stage.html">Stage</a></li>
140
141 <li><a href="../classes/StageGL.html">StageGL</a></li>
142
143 <li><a href="../classes/Text.html">Text</a></li>
144
145 <li><a href="../classes/Ticker.html">Ticker</a></li>
146
147 <li><a href="../classes/Touch.html">Touch</a></li>
148
149 <li><a href="../classes/UID.html">UID</a></li>
150
151 <li><a href="../classes/Utility Methods.html">Utility Methods</a></li>
152
153 <li><a href="../classes/VideoBuffer.html">VideoBuffer</a></li>
154
155 <li><a href="../classes/WebGLInspector.html">WebGLInspector</a></li>
156
157 </ul>
158
159 <ul id="api-modules" class="apis modules">
160
161 <li><a href="../modules/CreateJS.html">CreateJS</a></li>
162
163 <li><a href="../modules/EaselJS.html">EaselJS</a></li>
164
165 </ul>
166 </div>
167 </div>
168</div>
169
170 </div>
171 </div>
172 <div class="yui3-u-3-4">
173 <div id="api-options">
174 Show:
175 <label for="api-show-inherited">
176 <input type="checkbox" id="api-show-inherited" checked>
177 Inherited
178 </label>
179
180 <label for="api-show-protected">
181 <input type="checkbox" id="api-show-protected">
182 Protected
183 </label>
184
185 <label for="api-show-private">
186 <input type="checkbox" id="api-show-private">
187 Private
188 </label>
189 <label for="api-show-deprecated">
190 <input type="checkbox" id="api-show-deprecated">
191 Deprecated
192 </label>
193
194 </div>
195 <div class="apidocs">
196 <div id="docs-main">
197 <div class="content source-content">
198 <script>
199 var name = easeljs/display/SpriteSheet.js
200</script>
201<h1 class="file-heading">File:SpriteSheet.js</h1>
202
203<div class="file">
204 <pre class="code prettyprint linenums">
205/*
206 * SpriteSheet
207 * Visit http://createjs.com/ for documentation, updates and examples.
208 *
209 * Copyright (c) 2010 gskinner.com, inc.
210 *
211 * Permission is hereby granted, free of charge, to any person
212 * obtaining a copy of this software and associated documentation
213 * files (the "Software"), to deal in the Software without
214 * restriction, including without limitation the rights to use,
215 * copy, modify, merge, publish, distribute, sublicense, and/or sell
216 * copies of the Software, and to permit persons to whom the
217 * Software is furnished to do so, subject to the following
218 * conditions:
219 *
220 * The above copyright notice and this permission notice shall be
221 * included in all copies or substantial portions of the Software.
222 *
223 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
224 * EXPRESS OR IMPliED, INCLUDING BUT NOT liMITED TO THE WARRANTIES
225 * OF MERCHANTABIliTY, FITNESS FOR A PARTICULAR PURPOSE AND
226 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
227 * HolDERS BE liABLE FOR ANY CLAIM, DAMAGES OR OTHER liABIliTY,
228 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
229 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
230 * OTHER DEAliNGS IN THE SOFTWARE.
231 */
232
233/**
234 * @module EaselJS
235 */
236
237// namespace:
238this.createjs = this.createjs||{};
239
240(function() {
241 "use strict";
242
243
244// constructor:
245 /**
246 * Encapsulates the properties and methods associated with a sprite sheet. A sprite sheet is a series of images (usually
247 * animation frames) combined into a larger image (or images). For example, an animation consisting of eight 100x100
248 * images could be combined into a single 400x200 sprite sheet (4 frames across by 2 high).
249 *
250 * The data passed to the SpriteSheet constructor defines:
251 * <ol>
252 * <li> The source image or images to use.</li>
253 * <li> The positions of individual image frames.</li>
254 * <li> Sequences of frames that form named animations. Optional.</li>
255 * <li> The target playback framerate. Optional.</li>
256 * </ol>
257 * <h3>SpriteSheet Format</h3>
258 * SpriteSheets are an object with two required properties (`images` and `frames`), and two optional properties
259 * (`framerate` and `animations`). This makes them easy to define in javascript code, or in JSON.
260 *
261 * <h4>images</h4>
262 * An array of source images. Images can be either an HTMlimage
263 * instance, or a uri to an image. The former is recommended to control preloading.
264 *
265 * images: [image1, "path/to/image2.png"],
266 *
267 * <h4>frames</h4>
268 * Defines the individual frames. There are two supported formats for frame data:
269 * When all of the frames are the same size (in a grid), use an object with `width`, `height`, `regX`, `regY`,
270 * and `count` properties.
271 *
272 * <ul>
273 * <li>`width` & `height` are required and specify the dimensions of the frames</li>
274 * <li>`regX` & `regY` indicate the registration point or "origin" of the frames</li>
275 * <li>`spacing` indicate the spacing between frames</li>
276 * <li>`margin` specify the margin around the image(s)</li>
277 * <li>`count` allows you to specify the total number of frames in the spritesheet; if omitted, this will
278 * be calculated based on the dimensions of the source images and the frames. Frames will be assigned
279 * indexes based on their position in the source images (left to right, top to bottom).</li>
280 * </ul>
281 *
282 * frames: {width:64, height:64, count:20, regX: 32, regY:64, spacing:0, margin:0}
283 *
284 * If the frames are of different sizes, use an array of frame definitions. Each definition is itself an array
285 * with 4 required and 3 optional entries, in the order:
286 *
287 * <ul>
288 * <li>The first four, `x`, `y`, `width`, and `height` are required and define the frame rectangle.</li>
289 * <li>The fifth, `imageIndex`, specifies the index of the source image (defaults to 0)</li>
290 * <li>The last two, `regX` and `regY` specify the registration point of the frame</li>
291 * </ul>
292 *
293 * frames: [
294 * // x, y, width, height, imageIndex*, regX*, regY*
295 * [64, 0, 96, 64],
296 * [0, 0, 64, 64, 1, 32, 32]
297 * // etc.
298 * ]
299 *
300 * <h4>animations</h4>
301 * Optional. An object defining sequences of frames to play as named animations. Each property corresponds to an
302 * animation of the same name. Each animation must specify the frames to play, and may
303 * also include a relative playback `speed` (ex. 2 would playback at double speed, 0.5 at half), and
304 * the name of the `next` animation to sequence to after it completes.
305 *
306 * There are three formats supported for defining the frames in an animation, which can be mixed and matched as appropriate:
307 * <ol>
308 * <li>for a single frame animation, you can simply specify the frame index
309 *
310 * animations: {
311 * sit: 7
312 * }
313 *
314 * </li>
315 * <li>
316 * for an animation of consecutive frames, you can use an array with two required, and two optional entries
317 * in the order: `start`, `end`, `next`, and `speed`. This will play the frames from start to end inclusive.
318 *
319 * animations: {
320 * // start, end, next*, speed*
321 * run: [0, 8],
322 * jump: [9, 12, "run", 2]
323 * }
324 *
325 * </li>
326 * <li>
327 * for non-consecutive frames, you can use an object with a `frames` property defining an array of frame
328 * indexes to play in order. The object can also specify `next` and `speed` properties.
329 *
330 * animations: {
331 * walk: {
332 * frames: [1,2,3,3,2,1]
333 * },
334 * shoot: {
335 * frames: [1,4,5,6],
336 * next: "walk",
337 * speed: 0.5
338 * }
339 * }
340 *
341 * </li>
342 * </ol>
343 * <strong>Note:</strong> the `speed` property was added in EaselJS 0.7.0. Earlier versions had a `frequency`
344 * property instead, which was the inverse of `speed`. For example, a value of "4" would be 1/4 normal speed in
345 * earlier versions, but is 4x normal speed in EaselJS 0.7.0+.
346 *
347 * <h4>framerate</h4>
348 * Optional. Indicates the default framerate to play this spritesheet at in frames per second. See
349 * {{#crossLink "SpriteSheet/framerate:property"}}{{/crossLink}} for more information.
350 *
351 * framerate: 20
352 *
353 * Note that the Sprite framerate will only work if the stage update method is provided with the {{#crossLink "Ticker/tick:event"}}{{/crossLink}}
354 * event generated by the {{#crossLink "Ticker"}}{{/crossLink}}.
355 *
356 * createjs.Ticker.on("tick", handleTick);
357 * function handleTick(event) {
358 * stage.update(event);
359 * }
360 *
361 * <h3>Example</h3>
362 * To define a simple sprite sheet, with a single image "sprites.jpg" arranged in a regular 50x50 grid with three
363 * animations: "stand" showing the first frame, "run" looping frame 1-5 inclusive, and "jump" playing frame 6-8 and
364 * sequencing back to run.
365 *
366 * var data = {
367 * images: ["sprites.jpg"],
368 * frames: {width:50, height:50},
369 * animations: {
370 * stand:0,
371 * run:[1,5],
372 * jump:[6,8,"run"]
373 * }
374 * };
375 * var spriteSheet = new createjs.SpriteSheet(data);
376 * var animation = new createjs.Sprite(spriteSheet, "run");
377 *
378 * <h3>Generating SpriteSheet Images</h3>
379 * Spritesheets can be created manually by combining images in PhotoShop, and specifying the frame size or
380 * coordinates manually, however there are a number of tools that facilitate this.
381 * <ul>
382 * <li>Exporting SpriteSheets or HTML5 content from Adobe Flash/Animate supports the EaselJS SpriteSheet format.</li>
383 * <li>The popular <a href="https://www.codeandweb.com/texturepacker/easeljs" target="_blank">Texture Packer</a> has
384 * EaselJS support.
385 * <li>SWF animations in Adobe Flash/Animate can be exported to SpriteSheets using <a href="http://createjs.com/zoe" target="_blank">Zo&euml;</a></li>
386 * </ul>
387 *
388 * <h3>Cross Origin Issues</h3>
389 * <strong>Warning:</strong> Images loaded cross-origin will throw cross-origin security errors when interacted with
390 * using:
391 * <ul>
392 * <li>a mouse</li>
393 * <li>methods such as {{#crossLink "Container/getObjectUnderPoint"}}{{/crossLink}}</li>
394 * <li>Filters (see {{#crossLink "Filter"}}{{/crossLink}})</li>
395 * <li>caching (see {{#crossLink "DisplayObject/cache"}}{{/crossLink}})</li>
396 * </ul>
397 * You can get around this by setting `crossOrigin` property on your images before passing them to EaselJS, or
398 * setting the `crossOrigin` property on PreloadJS' LoadQueue or LoadItems.
399 *
400 * var image = new Image();
401 * img.crossOrigin="Anonymous";
402 * img.src = "http://server-with-CORS-support.com/path/to/image.jpg";
403 *
404 * If you pass string paths to SpriteSheets, they will not work cross-origin. The server that stores the image must
405 * support cross-origin requests, or this will not work. For more information, check out
406 * <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS" target="_blank">CORS overview on MDN</a>.
407 *
408 * @class SpriteSheet
409 * @constructor
410 * @param {Object} data An object describing the SpriteSheet data.
411 * @extends EventDispatcher
412 **/
413 function SpriteSheet(data) {
414 this.EventDispatcher_constructor();
415
416
417 // public properties:
418 /**
419 * Indicates whether all images are finished loading.
420 * @property complete
421 * @type Boolean
422 * @readonly
423 **/
424 this.complete = true;
425
426 /**
427 * Specifies the framerate to use by default for Sprite instances using the SpriteSheet. See the Sprite class
428 * {{#crossLink "Sprite/framerate:property"}}{{/crossLink}} for more information.
429 * @property framerate
430 * @type Number
431 **/
432 this.framerate = 0;
433
434
435 // private properties:
436 /**
437 * @property _animations
438 * @protected
439 * @type Array
440 **/
441 this._animations = null;
442
443 /**
444 * @property _frames
445 * @protected
446 * @type Array
447 **/
448 this._frames = null;
449
450 /**
451 * @property _images
452 * @protected
453 * @type Array
454 **/
455 this._images = null;
456
457 /**
458 * @property _data
459 * @protected
460 * @type Object
461 **/
462 this._data = null;
463
464 /**
465 * @property _loadCount
466 * @protected
467 * @type Number
468 **/
469 this._loadCount = 0;
470
471 // only used for simple frame defs:
472 /**
473 * @property _frameHeight
474 * @protected
475 * @type Number
476 **/
477 this._frameHeight = 0;
478
479 /**
480 * @property _frameWidth
481 * @protected
482 * @type Number
483 **/
484 this._frameWidth = 0;
485
486 /**
487 * @property _numFrames
488 * @protected
489 * @type Number
490 **/
491 this._numFrames = 0;
492
493 /**
494 * @property _regX
495 * @protected
496 * @type Number
497 **/
498 this._regX = 0;
499
500 /**
501 * @property _regY
502 * @protected
503 * @type Number
504 **/
505 this._regY = 0;
506
507 /**
508 * @property _spacing
509 * @protected
510 * @type Number
511 **/
512 this._spacing = 0;
513
514 /**
515 * @property _margin
516 * @protected
517 * @type Number
518 **/
519 this._margin = 0;
520
521 // setup:
522 this._parseData(data);
523 }
524 var p = createjs.extend(SpriteSheet, createjs.EventDispatcher);
525
526 // TODO: deprecated
527 // p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.
528
529
530// events:
531 /**
532 * Dispatched when all images are loaded. Note that this only fires if the images
533 * were not fully loaded when the sprite sheet was initialized. You should check the complete property
534 * to prior to adding a listener. Ex.
535 *
536 * var sheet = new createjs.SpriteSheet(data);
537 * if (!sheet.complete) {
538 * // not preloaded, listen for the complete event:
539 * sheet.addEventListener("complete", handler);
540 * }
541 *
542 * @event complete
543 * @param {Object} target The object that dispatched the event.
544 * @param {String} type The event type.
545 * @since 0.6.0
546 */
547
548 /**
549 * Dispatched when getFrame is called with a valid frame index. This is primarily intended for use by {{#crossLink "SpriteSheetBuilder"}}{{/crossLink}}
550 * when doing on-demand rendering.
551 * @event getframe
552 * @param {Number} index The frame index.
553 * @param {Object} frame The frame object that getFrame will return.
554 */
555
556 /**
557 * Dispatched when an image encounters an error. A SpriteSheet will dispatch an error event for each image that
558 * encounters an error, and will still dispatch a {{#crossLink "SpriteSheet/complete:event"}}{{/crossLink}}
559 * event once all images are finished processing, even if an error is encountered.
560 * @event error
561 * @param {String} src The source of the image that failed to load.
562 * @since 0.8.2
563 */
564
565
566// getter / setters:
567 /**
568 * Use the {{#crossLink "SpriteSheet/animations:property"}}{{/crossLink}} property instead.
569 * @method _getAnimations
570 * @protected
571 * @return {Array}
572 **/
573 p._getAnimations = function() {
574 return this._animations.slice();
575 };
576 // SpriteSheet.getAnimations is @deprecated. Remove for 1.1+
577 p.getAnimations = createjs.deprecate(p._getAnimations, "SpriteSheet.getAnimations");
578
579 /**
580 * Returns an array of all available animation names available on this sprite sheet as strings.
581 * @property animations
582 * @type {Array}
583 * @readonly
584 **/
585 try {
586 Object.defineProperties(p, {
587 animations: { get: p._getAnimations }
588 });
589 } catch (e) {}
590
591
592// public methods:
593 /**
594 * Returns the total number of frames in the specified animation, or in the whole sprite
595 * sheet if the animation param is omitted. Returns 0 if the spritesheet relies on calculated frame counts, and
596 * the images have not been fully loaded.
597 * @method getNumFrames
598 * @param {String} animation The name of the animation to get a frame count for.
599 * @return {Number} The number of frames in the animation, or in the entire sprite sheet if the animation param is omitted.
600 */
601 p.getNumFrames = function(animation) {
602 if (animation == null) {
603 return this._frames ? this._frames.length : this._numFrames || 0;
604 } else {
605 var data = this._data[animation];
606 if (data == null) { return 0; }
607 else { return data.frames.length; }
608 }
609 };
610
611 /**
612 * Returns an object defining the specified animation. The returned object contains:<UL>
613 * <li>frames: an array of the frame ids in the animation</li>
614 * <li>speed: the playback speed for this animation</li>
615 * <li>name: the name of the animation</li>
616 * <li>next: the default animation to play next. If the animation loops, the name and next property will be the
617 * same.</li>
618 * </UL>
619 * @method getAnimation
620 * @param {String} name The name of the animation to get.
621 * @return {Object} a generic object with frames, speed, name, and next properties.
622 **/
623 p.getAnimation = function(name) {
624 return this._data[name];
625 };
626
627 /**
628 * Returns an object specifying the image and source rect of the specified frame. The returned object has:<UL>
629 * <li>an image property holding a reference to the image object in which the frame is found</li>
630 * <li>a rect property containing a Rectangle instance which defines the boundaries for the frame within that
631 * image.</li>
632 * <li> A regX and regY property corresponding to the regX/Y values for the frame.
633 * </UL>
634 * @method getFrame
635 * @param {Number} frameIndex The index of the frame.
636 * @return {Object} a generic object with image and rect properties. Returns null if the frame does not exist.
637 **/
638 p.getFrame = function(frameIndex) {
639 var frame;
640 if (this._frames && (frame=this._frames[frameIndex])) { return frame; }
641 return null;
642 };
643
644 /**
645 * Returns a {{#crossLink "Rectangle"}}{{/crossLink}} instance defining the bounds of the specified frame relative
646 * to the origin. For example, a 90 x 70 frame with a regX of 50 and a regY of 40 would return:
647 *
648 * [x=-50, y=-40, width=90, height=70]
649 *
650 * @method getFrameBounds
651 * @param {Number} frameIndex The index of the frame.
652 * @param {Rectangle} [rectangle] A Rectangle instance to copy the values into. By default a new instance is created.
653 * @return {Rectangle} A Rectangle instance. Returns null if the frame does not exist, or the image is not fully loaded.
654 **/
655 p.getFrameBounds = function(frameIndex, rectangle) {
656 var frame = this.getFrame(frameIndex);
657 return frame ? (rectangle||new createjs.Rectangle()).setValues(-frame.regX, -frame.regY, frame.rect.width, frame.rect.height) : null;
658 };
659
660 /**
661 * Returns a string representation of this object.
662 * @method toString
663 * @return {String} a string representation of the instance.
664 **/
665 p.toString = function() {
666 return "[SpriteSheet]";
667 };
668
669 /**
670 * SpriteSheet cannot be cloned. A SpriteSheet can be shared by multiple Sprite instances without cloning it.
671 * @method clone
672 **/
673 p.clone = function() {
674 throw("SpriteSheet cannot be cloned.")
675 };
676
677// private methods:
678 /**
679 * @method _parseData
680 * @param {Object} data An object describing the SpriteSheet data.
681 * @protected
682 **/
683 p._parseData = function(data) {
684 var i,l,o,a;
685 if (data == null) { return; }
686
687 this.framerate = data.framerate||0;
688
689 // parse images:
690 if (data.images && (l=data.images.length) > 0) {
691 a = this._images = [];
692 for (i=0; i<l; i++) {
693 var img = data.images[i];
694 if (typeof img == "string") {
695 var src = img;
696 img = document.createElement("img");
697 img.src = src;
698 }
699 a.push(img);
700 if (!img.getContext && !img.naturalWidth) {
701 this._loadCount++;
702 this.complete = false;
703 (function(o, src) { img.onload = function() { o._handleImageLoad(src); } })(this, src);
704 (function(o, src) { img.onerror = function() { o._handleImageError(src); } })(this, src);
705 }
706 }
707 }
708
709 // parse frames:
710 if (data.frames == null) { // nothing
711 } else if (Array.isArray(data.frames)) {
712 this._frames = [];
713 a = data.frames;
714 for (i=0,l=a.length;i<l;i++) {
715 var arr = a[i];
716 this._frames.push({image:this._images[arr[4]?arr[4]:0], rect:new createjs.Rectangle(arr[0],arr[1],arr[2],arr[3]), regX:arr[5]||0, regY:arr[6]||0 });
717 }
718 } else {
719 o = data.frames;
720 this._frameWidth = o.width;
721 this._frameHeight = o.height;
722 this._regX = o.regX||0;
723 this._regY = o.regY||0;
724 this._spacing = o.spacing||0;
725 this._margin = o.margin||0;
726 this._numFrames = o.count;
727 if (this._loadCount == 0) { this._calculateFrames(); }
728 }
729
730 // parse animations:
731 this._animations = [];
732 if ((o=data.animations) != null) {
733 this._data = {};
734 var name;
735 for (name in o) {
736 var anim = {name:name};
737 var obj = o[name];
738 if (typeof obj == "number") { // single frame
739 a = anim.frames = [obj];
740 } else if (Array.isArray(obj)) { // simple
741 if (obj.length == 1) { anim.frames = [obj[0]]; }
742 else {
743 anim.speed = obj[3];
744 anim.next = obj[2];
745 a = anim.frames = [];
746 for (i=obj[0];i<=obj[1];i++) {
747 a.push(i);
748 }
749 }
750 } else { // complex
751 anim.speed = obj.speed;
752 anim.next = obj.next;
753 var frames = obj.frames;
754 a = anim.frames = (typeof frames == "number") ? [frames] : frames.slice(0);
755 }
756 if (anim.next === true || anim.next === undefined) { anim.next = name; } // loop
757 if (anim.next === false || (a.length < 2 && anim.next == name)) { anim.next = null; } // stop
758 if (!anim.speed) { anim.speed = 1; }
759 this._animations.push(name);
760 this._data[name] = anim;
761 }
762 }
763 };
764
765 /**
766 * @method _handleImageLoad
767 * @protected
768 **/
769 p._handleImageLoad = function(src) {
770 if (--this._loadCount == 0) {
771 this._calculateFrames();
772 this.complete = true;
773 this.dispatchEvent("complete");
774 }
775 };
776
777 /**
778 * @method _handleImageError
779 * @protected
780 */
781 p._handleImageError = function (src) {
782 var errorEvent = new createjs.Event("error");
783 errorEvent.src = src;
784 this.dispatchEvent(errorEvent);
785
786 // Complete is still dispatched.
787 if (--this._loadCount == 0) {
788 this.dispatchEvent("complete");
789 }
790 };
791
792 /**
793 * @method _calculateFrames
794 * @protected
795 **/
796 p._calculateFrames = function() {
797 if (this._frames || this._frameWidth == 0) { return; }
798
799 this._frames = [];
800
801 var maxFrames = this._numFrames || 100000; // if we go over this, something is wrong.
802 var frameCount = 0, frameWidth = this._frameWidth, frameHeight = this._frameHeight;
803 var spacing = this._spacing, margin = this._margin;
804
805 imgLoop:
806 for (var i=0, imgs=this._images; i<imgs.length; i++) {
807 var img = imgs[i], imgW = (img.width||img.naturalWidth), imgH = (img.height||img.naturalHeight);
808
809 var y = margin;
810 while (y <= imgH-margin-frameHeight) {
811 var x = margin;
812 while (x <= imgW-margin-frameWidth) {
813 if (frameCount >= maxFrames) { break imgLoop; }
814 frameCount++;
815 this._frames.push({
816 image: img,
817 rect: new createjs.Rectangle(x, y, frameWidth, frameHeight),
818 regX: this._regX,
819 regY: this._regY
820 });
821 x += frameWidth+spacing;
822 }
823 y += frameHeight+spacing;
824 }
825 }
826 this._numFrames = frameCount;
827 };
828
829
830 createjs.SpriteSheet = createjs.promote(SpriteSheet, "EventDispatcher");
831}());
832
833 </pre>
834</div>
835
836 </div>
837 </div>
838 </div>
839 </div>
840 </div>
841</div>
842<script src="../assets/vendor/prettify/prettify-min.js"></script>
843<script>prettyPrint();</script>
844<script src="../assets/js/yui-prettify.js"></script>
845<script src="../assets/../api.js"></script>
846<script src="../assets/js/api-filter.js"></script>
847<script src="../assets/js/api-list.js"></script>
848<script src="../assets/js/api-search.js"></script>
849<script src="../assets/js/apidocs.js"></script>
850</body>
851</html>