Container Class
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 Bitmap 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 Shape 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;
Constructor
Container
()
Item Index
Methods
- _applyFilters
- _applyShadow
- _getObjectsUnderPoint
- _hasMouseHandler
- _testHit
- _tick
- addChild
- addChildAt
- addEventListener
- cache
- clone
- cloneProps
- contains
- dispatchEvent
- draw
- getCacheDataURL.
- getChildAt
- getChildByName
- getChildIndex
- getConcatenatedMatrix
- getMatrix
- getNumChildren
- getObjectsUnderPoint
- getObjectUnderPoint
- getStage
- globalToLocal
- hasEventListener
- hitTest
- initialize
- isVisible
- localToGlobal
- localToLocal
- removeAllChildren
- removeAllEventListeners
- removeChild
- removeChildAt
- removeEventListener
- set
- setChildIndex
- setTransform
- sortChildren
- swapChildren
- swapChildrenAt
- toString
- uncache
- updateCache
- updateContext
Properties
- _cacheDataURL
- _cacheDataURLID
- _cacheOffsetX
- _cacheOffsetY
- _cacheScale
- _listeners
- _matrix
- alpha
- cacheCanvas
- cacheID
- children
- compositeOperation
- cursor
- DisplayObject__tick
- DisplayObject_draw
- DisplayObject_initialize
- filters
- hitArea
- id
- mask
- mouseEnabled
- name
- onClick deprecated
- onDoubleClick deprecated
- onMouseOut deprecated
- onMouseOver deprecated
- onPress deprecated
- onTick deprecated
- parent
- regX
- regY
- rotation
- scaleX
- scaleY
- shadow
- skewX
- skewY
- snapToPixel deprecated
- visible
- x
- y
Methods
_applyFilters
()
protected
_hasMouseHandler
-
typeMask
Indicates whether the display object has a listener of the corresponding event types.
Parameters:
-
typeMask
NumberA bitmask indicating which event types to look for. Bit 1 specifies press & click & double click, bit 2 specifies it should look for mouse over and mouse out. This implementation may change.
Returns:
_tick
()
protected
addChild
-
child
Adds a child to the top of the display list.
Example
container.addChild(bitmapInstance);
You can also add multiple children at once:
container.addChild(bitmapInstance, shapeInstance, textInstance);
Parameters:
-
child
DisplayObjectThe display object to add.
Returns:
addChildAt
-
child
-
index
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.
Parameters:
-
child
DisplayObjectThe display object to add.
-
index
NumberThe index to add the child at.
Returns:
addEventListener
-
type
-
listener
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:
cache
-
x
-
y
-
width
-
height
-
[scale=1]
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 it's 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 Filter class for more information.
Parameters:
-
x
NumberThe x coordinate origin for the cache region.
-
y
NumberThe y coordinate origin for the cache region.
-
width
NumberThe width of the cache region.
-
height
NumberThe height of the cache region.
-
[scale=1]
Number optionalThe 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.
clone
-
recursive
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).
Parameters:
-
recursive
BooleanIf 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.
Returns:
cloneProps
-
o
Parameters:
-
o
DisplayObjectThe DisplayObject instance which will have properties from the current DisplayObject instance copied into.
contains
-
child
Returns true if the specified display object either is this container or is a descendent (child, grandchild, etc) of this container.
Parameters:
-
child
DisplayObjectThe DisplayObject to be checked.
Returns:
dispatchEvent
-
eventObj
-
[target]
Dispatches the specified event to all listeners.
Example
// Use a string event
this.dispatchEvent("complete");
// Use an object
var event = {
type: "complete",
foo: "bar"
};
this.dispatchEvent(event);
Parameters:
-
eventObj
Object | StringAn object with a "type" property, or a string type. If a string is used, dispatchEvent will construct a generic event object with the specified type.
-
[target]
Object optionalThe object to use as the target property of the event object. This will default to the dispatching object.
Returns:
draw
-
ctx
-
[ignoreCache=false]
Draws the display object into the specified context ignoring it's 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.
Parameters:
-
ctx
CanvasRenderingContext2DThe canvas 2D context object to draw into.
-
[ignoreCache=false]
Boolean optionalIndicates 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).
getCacheDataURL.
()
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.
getChildAt
-
index
Returns the child at the specified index.
Example
container.getChildAt(2);
Parameters:
-
index
NumberThe index of the child to return.
Returns:
getChildByName
-
name
Returns the child with the specified name.
Parameters:
-
name
StringThe name of the child to return.
Returns:
getChildIndex
-
child
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);
Parameters:
-
child
DisplayObjectThe child to return the index of.
Returns:
getConcatenatedMatrix
-
[mtx]
Generates a concatenated Matrix2D object representing the combined transform of the display object and all of its parent Containers up to the highest level ancestor (usually the Stage). This can be used to transform positions between coordinate spaces, such as with localToGlobal and globalToLocal.
Parameters:
getMatrix
-
matrix
Returns a matrix based on this object's transform.
Parameters:
-
matrix
Matrix2DOptional. A Matrix2D object to populate with the calculated values. If null, a new Matrix object is returned.
Returns:
getNumChildren
()
Number
Returns the number of children in the display list.
Returns:
getObjectsUnderPoint
-
x
-
y
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 mouseEnabled 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 mousemove), and only if the mouse's position has changed.
Parameters:
Returns:
getObjectUnderPoint
-
x
-
y
Similar to Container/getObjectsUnderPoint(), but returns only the top-most display
object. This runs significantly faster than getObjectsUnderPoint()
, but is still an expensive
operation. See getObjectsUnderPoint for more information.
Parameters:
Returns:
getStage
()
Stage
Returns the stage that this display object will be rendered on, or null if it has not been added to one.
Returns:
globalToLocal
-
x
-
y
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
Parameters:
Returns:
hasEventListener
-
type
Indicates whether there is at least one listener for the specified event type.
Parameters:
-
type
StringThe string type of the event.
Returns:
hitTest
-
x
-
y
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.
Parameters:
Returns:
initialize
()
protected
Initialization method.
isVisible
()
Boolean
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.
Returns:
localToGlobal
-
x
-
y
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 = myDisplayObject.localToGlobal(100, 100);
// Results in x=400, y=300
Parameters:
Returns:
localToLocal
-
x
-
y
-
target
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 localToGlobal and globalToLocal.
var pt = this.localToGlobal(x, y);
pt = target.globalToLocal(pt.x, pt.y);
Parameters:
-
x
NumberThe x position in the source display object to transform.
-
y
NumberThe y position on the stage to transform.
-
target
DisplayObjectThe target display object to which the coordinates will be transformed.
Returns:
removeAllChildren
()
Removes all children from the display list.
Example
container.removeAlLChildren();
removeAllEventListeners
-
[type]
Removes all listeners for the specified type, or all listeners of all types.
Example
// Remove all listeners
displayObject.removeAllEvenListeners();
// 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.
removeChild
-
child
Removes the specified child from the display list. Note that it is faster to use removeChildAt() if the index is already known.
Example
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.
Parameters:
-
child
DisplayObjectThe child to remove.
Returns:
removeChildAt
-
index
Removes the child at the specified index from the display list, and sets its parent to null.
Example
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.
Parameters:
-
index
NumberThe index of the child to remove.
Returns:
removeEventListener
-
type
-
listener
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);
set
-
props
Provides a chainable shortcut method for setting a number of properties on a DisplayObject 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});
Parameters:
-
props
ObjectA generic object containing properties to copy to the DisplayObject instance.
Returns:
setChildIndex
-
child
-
index
Changes the depth of the specified child. Fails silently if the child is not a child of this container, or the index is out of range.
Parameters:
-
child
DisplayObject -
index
Number
setTransform
-
[x=0]
-
[y=0]
-
[scaleX=1]
-
[scaleY=1]
-
[rotation=0]
-
[skewX=0]
-
[skewY=0]
-
[regX=0]
-
[regY=0]
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);
Parameters:
-
[x=0]
Number optionalThe horizontal translation (x position) in pixels
-
[y=0]
Number optionalThe vertical translation (y position) in pixels
-
[scaleX=1]
Number optionalThe horizontal scale, as a percentage of 1
-
[scaleY=1]
Number optionalthe vertical scale, as a percentage of 1
-
[rotation=0]
Number optionalThe rotation, in degrees
-
[skewX=0]
Number optionalThe horizontal skew factor
-
[skewY=0]
Number optionalThe vertical skew factor
-
[regX=0]
Number optionalThe horizontal registration point in pixels
-
[regY=0]
Number optionalThe vertical registration point in pixels
Returns:
sortChildren
-
sortFunction
Performs an array sort operation on the child list.
Example
var sortFunction = function(item1, item2, options) {
if (item1 > item2) { return 1; }
if (item1 < item2) { return -1; }
return 0;
}
container.sortChildren(sortFunction);
Parameters:
-
sortFunction
Functionthe function to use to sort the child list. See JavaScript's
Array.sort
documentation for details.
swapChildren
-
child1
-
child2
Swaps the specified children's depth in the display list. Fails silently if either child is not a child of this Container.
Parameters:
-
child1
DisplayObject -
child2
DisplayObject
swapChildrenAt
-
index1
-
index2
Swaps the children at the specified indexes. Fails silently if either index is out of range.
toString
()
String
Returns a string representation of this object.
Returns:
updateCache
-
compositeOperation
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();
Parameters:
-
compositeOperation
StringThe compositeOperation to use, or null to clear the cache and redraw it. whatwg spec on compositing.
updateContext
-
ctx
Applies this display object's transformation, alpha, globalCompositeOperation, clipping path (mask), and shadow to the specified context. This is typically called prior to draw.
Parameters:
-
ctx
CanvasRenderingContext2DThe canvas 2D to update.
Properties
alpha
Number
The alpha (transparency) for this display object. 0 is fully transparent, 1 is fully opaque.
Default: 1
cacheCanvas
HTMLCanvasElement | Object
If a cache is active, this returns the canvas that holds the cached version of this display object. See cache() for more information. READ-ONLY.
Default: null
cacheID
Number
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.
Default: 0
children
Array
The array of children in the display list. You should usually use the child management methods such as addChild, removeChild, swapChildren, etc, rather than accessing this directly, but it is included for advanced uses.
Default: null
compositeOperation
String
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.
Default: null
cursor
String
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 enableMouseOver method to use this property. If null it will use the default cursor.
Default: null
filters
Array
An array of Filter objects to apply to this display object. Filters are only applied / updated when cache()
or
updateCache()
is called on the display object, and only apply to the area that is cached.
Default: null
hitArea
DisplayObject
A display object that will be tested when checking mouse interactions or testing getObjectsUnderPoint.
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).
Note that hitArea is NOT currently used by the hitTest()
method, nor is it supported for Stage.
Default: null
id
Number
Unique ID for this display object. Makes display objects easier for some uses.
Default: -1
mask
Shape
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).
Default: null
mouseEnabled
Boolean
Indicates whether to include this object when running mouse interactions. Setting this to false
for children
of a Container will cause events on the Container to not fire when that child is
clicked. Note that setting this property to false
does not prevent the getObjectsUnderPoint
method from returning the child.
Default: true
name
String
An optional name for this display object. Included in toString(). Useful for debugging.
Default: null
onClick
Function
deprecated
The onClick callback is called when the user presses down on and then releases the mouse button over this display object. The handler is passed a single param containing the corresponding MouseEvent instance. If an onClick handler is set on a container, it will receive the event if any of its children are clicked.
onDoubleClick
Function
deprecated
The onDoubleClick callback is called when the user double clicks over this display object. The handler is passed a single param containing the corresponding MouseEvent instance. If an onDoubleClick handler is set on a container, it will receive the event if any of its children are clicked.
onMouseOut
Function
deprecated
The onMouseOut callback is called when the user rolls off of the display object. You must enable this event using stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance.
onMouseOver
Function
deprecated
The onMouseOver callback is called when the user rolls over the display object. You must enable this event using stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance.
onPress
Function
deprecated
The onPress callback is called when the user presses down on their mouse over this display object. The handler is passed a single param containing the corresponding MouseEvent instance. You can subscribe to the onMouseMove and onMouseUp callbacks of the event object to receive these events until the user releases the mouse button. If an onPress handler is set on a container, it will receive the event if any of its children are clicked.
onTick
Function
deprecated
The onTick callback is called on each display object on a stage whenever the stage updates.
This occurs immediately before the rendering (draw) pass. When stage.update() is called, first all display
objects on the stage have onTick called, then all of the display objects are drawn to stage. Children will have
their onTick
called in order of their depth prior to onTick being called on their parent.
Any parameters passed in to stage.update()
are passed on to the onTick()
handlers. For example, if you call
stage.update("hello")
, all of the display objects with a handler will have onTick("hello")
called.
parent
Container
final
A reference to the Container or Stage object that contains this display object, or null if it has not been added to one. READ-ONLY.
Default: null
regX
Number
The x offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around it's center, you would set regX and regY to 50.
Default: 0
regY
Number
The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around it's center, you would set regX and regY to 50.
Default: 0
scaleX
Number
The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display object to twice it's nominal width. To horizontally flip an object, set the scale to a negative number.
Default: 1
scaleY
Number
The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display object to half it's nominal height. To vertically flip an object, set the scale to a negative number.
Default: 1
shadow
Shadow
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.
Default: null
snapToPixel
Boolean
deprecated
Indicates whether the display object should have it's x & y position rounded prior to drawing it to stage.
Snapping to whole pixels can result in a sharper and faster draw for images (ex. Bitmap & cached objects).
This only applies if the enclosing stage has snapPixelsEnabled set to true. The snapToPixel property is true
by default for Bitmap and BitmapAnimation instances, and false for all other display objects.
Note that this applies only rounds the display object's local position. You should
ensure that all of the display object's ancestors (parent containers) are also on a whole pixel. You can do this
by setting the ancestors' snapToPixel property to true.
Default: false
visible
Boolean
Indicates whether this display object should be rendered to the canvas and included when running Stage.getObjectsUnderPoint().
Default: true
Events
click
Dispatched when the user presses their left mouse button and then releases it while over the display object. See the MouseEvent class for a listing of event properties.
dblclick
Dispatched when the user double clicks their left mouse button over this display object. See the MouseEvent class for a listing of event properties.
mousedown
Dispatched when the user presses their left mouse button over the display object. See the MouseEvent class for a listing of event properties.
mouseout
Dispatched when the user's mouse rolls out of this display object. This event must be enabled using enableMouseOver. See the MouseEvent class for a listing of event properties.
mouseover
Dispatched when the user's mouse rolls over this display object. This event must be enabled using Stage.enableMouseOver. See the MouseEvent class for a listing of event properties.
tick
Dispatched on each display object on a stage whenever the stage updates. This occurs immediately before the rendering (draw) pass. When update 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 tick event dispatched in order of their depth prior to the event being dispatched on their parent.