Please correct me if I’m wrong here, but I was looking for a method or property to retrieve the boundaries of a DisplayObject in EaselJS – however I was not able to find it – so I wrote my own method for this, maybe this will help someone and hopefully a method like this will be implemented into the framework in the future. If someone knows about the existence of such a method, please post it in the comments, so I can update this post.
Update (12-06-2012): I updated the snipped to work with the current easelJS version, it also includes rotation now.
Update (03-14-2013): Please refer to the following library: https://github.com/olsn/Collision-Detection-for-EaselJS it contains the getBounds()-method and is regularly updated and contains bugfixes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/* * Calculated the boundaries of an object. * * @method getBounds * @param {DisplayObject} the object to calculate the bounds from * @return {Rectangle} The rectangle describing the bounds of the object */ function getBounds(obj) { var bounds={x:Infinity,y:Infinity,width:0,height:0}; if ( obj instanceof createjs.Container ) { var children = obj.children, l=children.length, cbounds, c; for ( c = 0; c < l; c++ ) { cbounds = getBounds(children[c]); if ( cbounds.x < bounds.x ) bounds.x = cbounds.x; if ( cbounds.y < bounds.y ) bounds.y = cbounds.y; if ( cbounds.width > bounds.width ) bounds.width = cbounds.width; if ( cbounds.height > bounds.height ) bounds.height = cbounds.height; } } else { var gp,gp2,gp3,gp4,imgr; if ( obj instanceof createjs.Bitmap ) { imgr = obj.image; } else if ( obj instanceof createjs.BitmapAnimation ) { if ( obj.spriteSheet._frames && obj.spriteSheet._frames[obj.currentFrame] && obj.spriteSheet._frames[obj.currentFrame].image ) imgr = obj.spriteSheet.getFrame(obj.currentFrame).rect; else return bounds; } else { return bounds; } gp = obj.localToGlobal(0,0); gp2 = obj.localToGlobal(imgr.width,imgr.height); gp3 = obj.localToGlobal(imgr.width,0); gp4 = obj.localToGlobal(0,imgr.height); bounds.x = Math.min(Math.min(Math.min(gp.x,gp2.x),gp3.x),gp4.x); bounds.y = Math.min(Math.min(Math.min(gp.y,gp2.y),gp3.y),gp4.y); bounds.width = Math.max(Math.max(Math.max(gp.x,gp2.x),gp3.x),gp4.x) - bounds.x; bounds.height = Math.max(Math.max(Math.max(gp.y,gp2.y),gp3.y),gp4.y) - bounds.y; } return bounds; } |
Disclaimer: I did NO extensive testing on this method, if you find any bug, please post it in the comments, also I would like to point out that the method does NOT consider the rotation or skew parameters.
Pingback: Retro Style Plattform Runner Game for mobile with EaselJS (Part 2) | indiegamr