API Documentation for: 1.0.0
Show:

SpriteSheet Class

Extends EventDispatcher
Defined in: SpriteSheet:41
Module: EaselJS

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. The positions of individual image frames.
  3. Sequences of frames that form named animations. Optional.
  4. The target playback framerate. Optional.

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. 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 EaselJS 0.7.0+.

framerate

Optional. Indicates the default framerate to play this spritesheet at in frames per second. See framerate for more information.

    framerate: 20

Note that the Sprite framerate will only work if the stage update method is provided with the tick event generated by the Ticker.

    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 Adobe Flash/Animate supports the EaselJS SpriteSheet format.
  • The popular Texture Packer has EaselJS support.
  • SWF animations in Adobe Flash/Animate can be exported to SpriteSheets using Zoë

Cross Origin Issues

Warning: Images loaded cross-origin will throw cross-origin security errors when interacted with using:

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 img = 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.

Constructor

SpriteSheet

(
  • data
)

Defined in SpriteSheet:41

Parameters:

  • data Object

    An object describing the SpriteSheet data.

Methods

_calculateFrames

() protected

_dispatchEvent

(
  • eventObj
  • eventPhase
)
protected

Parameters:

_getAnimations

() Array protected

Defined in _getAnimations:363

Use the animations property instead.

Returns:

_handleImageError

() protected

_handleImageLoad

() protected

_parseData

(
  • data
)
protected

Defined in _parseData:480

Parameters:

  • data Object

    An object describing the SpriteSheet data.

addEventListener

(
  • type
  • listener
  • [useCapture]
)
Function | Object

Adds the specified event listener. Note that adding multiple listeners to the same function will result in multiple callbacks getting fired.

Example

 displayObject.addEventListener("click", handleClick);
 function handleClick(event) {
    // Click happened.
 }

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    An object with a handleEvent method, or a function that will be called when the event is dispatched.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

Returns:

Function | Object:

Returns the listener for chaining or assignment.

clone

()

Defined in clone:471

SpriteSheet cannot be cloned. A SpriteSheet can be shared by multiple Sprite instances without cloning it.

dispatchEvent

(
  • eventObj
  • [bubbles]
  • [cancelable]
)
Boolean

Dispatches the specified event to all listeners.

Example

 // Use a string event
 this.dispatchEvent("complete");

 // Use an Event instance
 var event = new createjs.Event("progress");
 this.dispatchEvent(event);

Parameters:

  • eventObj Object | String | Event

    An object with a "type" property, or a string type. While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used, dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can be used to avoid event object instantiation for non-bubbling events that may not have any listeners.

  • [bubbles] Boolean optional

    Specifies the bubbles value when a string was passed to eventObj.

  • [cancelable] Boolean optional

    Specifies the cancelable value when a string was passed to eventObj.

Returns:

Boolean:

Returns false if preventDefault() was called on a cancelable event, true otherwise.

getAnimation

(
  • name
)
Object

Defined in getAnimation:413

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.

Parameters:

  • name String

    The name of the animation to get.

Returns:

Object:

a generic object with frames, speed, name, and next properties.

getAnimations

() deprecated

Defined in getAnimations:373

Use the animations property instead.

getFrame

(
  • frameIndex
)
Object

Defined in getFrame:429

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.

Parameters:

  • frameIndex Number

    The index of the frame.

Returns:

Object:

a generic object with image and rect properties. Returns null if the frame does not exist.

getFrameBounds

(
  • frameIndex
  • [rectangle]
)
Rectangle

Defined in getFrameBounds:446

Returns a Rectangle 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]

Parameters:

  • frameIndex Number

    The index of the frame.

  • [rectangle] Rectangle optional

    A Rectangle instance to copy the values into. By default a new instance is created.

Returns:

Rectangle:

A Rectangle instance. Returns null if the frame does not exist, or the image is not fully loaded.

getNumFrames

(
  • animation
)
Number

Defined in getNumFrames:395

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.

Parameters:

  • animation String

    The name of the animation to get a frame count for.

Returns:

Number:

The number of frames in the animation, or in the entire sprite sheet if the animation param is omitted.

hasEventListener

(
  • type
)
Boolean

Indicates whether there is at least one listener for the specified event type.

Parameters:

  • type String

    The string type of the event.

Returns:

Boolean:

Returns true if there is at least one listener for the specified event.

off

(
  • type
  • listener
  • [useCapture]
)

Inherited from EventDispatcher: off:249

A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the .on method.

IMPORTANT: To remove a listener added with on, you must pass in the returned wrapper function as the listener. See on for an example.

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    The listener function or object.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

on

(
  • type
  • listener
  • [scope]
  • [once=false]
  • [data]
  • [useCapture=false]
)
Function

Inherited from EventDispatcher: on:173

A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener only run once, associate arbitrary data with the listener, and remove the listener.

This method works by creating an anonymous wrapper function and subscribing it with addEventListener. The wrapper function is returned for use with removeEventListener (or off).

IMPORTANT: To remove a listener added with on, you must pass in the returned wrapper function as the listener, or use remove. Likewise, each time you call on a NEW wrapper function is subscribed, so multiple calls to on with the same params will create multiple listeners.

Example

    var listener = myBtn.on("click", handleClick, null, false, {count:3});
    function handleClick(evt, data) {
        data.count -= 1;
        console.log(this == myBtn); // true - scope defaults to the dispatcher
        if (data.count == 0) {
            alert("clicked 3 times!");
            myBtn.off("click", listener);
            // alternately: evt.remove();
        }
    }

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    An object with a handleEvent method, or a function that will be called when the event is dispatched.

  • [scope] Object optional

    The scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent).

  • [once=false] Boolean optional

    If true, the listener will remove itself after the first time it is triggered.

  • [data] optional

    Arbitrary data that will be included as the second parameter when the listener is called.

  • [useCapture=false] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

Returns:

Function:

Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener.

removeAllEventListeners

(
  • [type]
)

Removes all listeners for the specified type, or all listeners of all types.

Example

 // Remove all listeners
 displayObject.removeAllEventListeners();

 // Remove all click listeners
 displayObject.removeAllEventListeners("click");

Parameters:

  • [type] String optional

    The string type of the event. If omitted, all listeners for all types will be removed.

removeEventListener

(
  • type
  • listener
  • [useCapture]
)

Removes the specified event listener.

Important Note: that you must pass the exact function reference used when the event was added. If a proxy function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or closure will not work.

Example

 displayObject.removeEventListener("click", handleClick);

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    The listener function or object.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

toString

() String

Inherited from EventDispatcher but overwritten in toString:462

Returns a string representation of this object.

Returns:

String:

a string representation of the instance.

willTrigger

(
  • type
)
Boolean

Indicates whether there is at least one listener for the specified event type on this object or any of its ancestors (parent, parent's parent, etc). A return value of true indicates that if a bubbling event of the specified type is dispatched from this object, it will trigger at least one listener.

This is similar to hasEventListener, but it searches the entire event flow for a listener, not just this object.

Parameters:

  • type String

    The string type of the event.

Returns:

Boolean:

Returns true if there is at least one listener for the specified event.

Properties

_animations

Array protected

Defined in _animations:232

_captureListeners

Object protected

_data

Object protected

Defined in _data:253

_frameHeight

Number protected

Defined in _frameHeight:268

_frames

Array protected

Defined in _frames:239

_frameWidth

Number protected

Defined in _frameWidth:275

_images

Array protected

Defined in _images:246

_listeners

Object protected

Inherited from EventDispatcher: _listeners:99

_loadCount

Number protected

Defined in _loadCount:260

_margin

Number protected

Defined in _margin:310

_numFrames

Number protected

Defined in _numFrames:282

_regX

Number protected

Defined in _regX:289

_regY

Number protected

Defined in _regY:296

_spacing

Number protected

Defined in _spacing:303

animations

Array readonly

Defined in animations:381

Returns an array of all available animation names available on this sprite sheet as strings.

complete

Boolean readonly

Defined in complete:214

Indicates whether all images are finished loading.

framerate

Number

Defined in framerate:222

Specifies the framerate to use by default for Sprite instances using the SpriteSheet. See the Sprite class framerate for more information.

Events

complete

Defined in complete:327

Available since 0.6.0

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 Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

error

Defined in error:352

Available since 0.8.2

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 complete event once all images are finished processing, even if an error is encountered.

Event Payload:

  • src String

    The source of the image that failed to load.

getframe

Defined in getframe:344

Dispatched when getFrame is called with a valid frame index. This is primarily intended for use by SpriteSheetBuilder when doing on-demand rendering.

Event Payload:

  • index Number

    The frame index.

  • frame Object

    The frame object that getFrame will return.