Since my previous post discussing why we don’t support width & height in EaselJS, I decided to polish off and include a bounds solution we had previously roughed out.
It comprises three new methods available on all display objects:
getBounds() method will return the bounds of the object in the object’s local coordinate system (relative to its nominal 0,0 with no transformations) as a
Rectangle instance. Where possible, it will return auto-calculated bounds. This includes accurate bounds for
Sprite, approximate bounds for
Text, and bounds for
Container that include all children that return a non-null
getBounds() value. For
Shape, it returns null by default.
For those object types that don’t calculate their own bounds (
Shape), you can manually specify bounds using
setBounds(x,y,w,h). This allows the object to participate in
Container bounds calculations. It can also be used to override the automatic calculation, to provide more accurate bounds for
Text for example, or to reduce bounds calculation costs on
cache() will similarly override calculated bounds with the cache’s defined bounds.
Here’s a table that describes how each display object works with
|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.|
|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).|
getTransformedBounds() returns the bounds of the object within its parent coordinate system (ie. with the object’s transformation applied).
Hopefully this balance between functionality, flexibility, and performance works for most users. We’re going to continue to evaluate options for dealing with Shape, and add support for more accurate Text bounds as additional canvas APIs become available.
As always, we’d love to hear your feedback.