SpriteSheet Class
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:
- The source image or images to use.
- The positions of individual image frames.
- Sequences of frames that form named animations. Optional.
- 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 withwidth
, height
, regX
, regY
,
and count
properties.
width
&height
are required and specify the dimensions of the framesregX
®Y
indicate the registration point or "origin" of the framesspacing
indicate the spacing between framesmargin
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
, andheight
are required and define the frame rectangle. - The fifth,
imageIndex
, specifies the index of the source image (defaults to 0) - The last two,
regX
andregY
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 playbackspeed
(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:
- for a single frame animation, you can simply specify the frame index
animations: { sit: 7 }
-
for an animation of consecutive frames, you can use an array with two required, and two optional entries
in the order:
start
,end
,next
, andspeed
. This will play the frames from start to end inclusive.animations: { // start, end, next*, speed* run: [0, 8], jump: [9, 12, "run", 2] }
-
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 specifynext
andspeed
properties.animations: { walk: { frames: [1,2,3,3,2,1] }, shoot: { frames: [1,4,5,6], next: "walk", speed: 0.5 } }
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:- a mouse
- methods such as getObjectUnderPoint
- Filters (see Filter)
- caching (see cache)
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
Item Index
Methods
Properties
Methods
_calculateFrames
()
protected
_dispatchEvent
-
eventObj
-
eventPhase
_handleImageError
()
protected
_handleImageLoad
()
protected
addEventListener
-
type
-
listener
-
[useCapture]
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
StringThe string type of the event.
-
listener
Function | ObjectAn object with a handleEvent method, or a function that will be called when the event is dispatched.
-
[useCapture]
Boolean optionalFor events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
clone
()
SpriteSheet cannot be cloned. A SpriteSheet can be shared by multiple Sprite instances without cloning it.
dispatchEvent
-
eventObj
-
[bubbles]
-
[cancelable]
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 | EventAn 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 optionalSpecifies the
bubbles
value when a string was passed to eventObj. -
[cancelable]
Boolean optionalSpecifies the
cancelable
value when a string was passed to eventObj.
Returns:
Returns false if preventDefault()
was called on a cancelable event, true otherwise.
getAnimation
-
name
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
StringThe name of the animation to get.
Returns:
a generic object with frames, speed, name, and next properties.
getFrame
-
frameIndex
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
NumberThe index of the frame.
Returns:
a generic object with image and rect properties. Returns null if the frame does not exist.
getFrameBounds
-
frameIndex
-
[rectangle]
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:
Returns:
A Rectangle instance. Returns null if the frame does not exist, or the image is not fully loaded.
getNumFrames
-
animation
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
StringThe name of the animation to get a frame count for.
Returns:
The number of frames in the animation, or in the entire sprite sheet if the animation param is omitted.
hasEventListener
-
type
Indicates whether there is at least one listener for the specified event type.
Parameters:
-
type
StringThe string type of the event.
Returns:
Returns true if there is at least one listener for the specified event.
off
-
type
-
listener
-
[useCapture]
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.
on
-
type
-
listener
-
[scope]
-
[once=false]
-
[data]
-
[useCapture=false]
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
StringThe string type of the event.
-
listener
Function | ObjectAn object with a handleEvent method, or a function that will be called when the event is dispatched.
-
[scope]
Object optionalThe 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 optionalIf true, the listener will remove itself after the first time it is triggered.
-
[data]
optionalArbitrary data that will be included as the second parameter when the listener is called.
-
[useCapture=false]
Boolean optionalFor events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
Returns:
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 optionalThe 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);
toString
()
String
Returns a string representation of this object.
Returns:
a string representation of the instance.
willTrigger
-
type
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
StringThe string type of the event.
Returns:
Returns true
if there is at least one listener for the specified event.
Properties
animations
Array
readonly
Returns an array of all available animation names available on this sprite sheet as strings.
Events
complete
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);
}
error
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
StringThe source of the image that failed to load.
getframe
Dispatched when getFrame is called with a valid frame index. This is primarily intended for use by SpriteSheetBuilder when doing on-demand rendering.