Search code examples
createjseaseljs

createjs global getTransformedBounds


I'd like to get an Bitmaps (or other Container) global bounds, i.e. the bounds of the Container on the stage after rotation, scale, position etc have been applied.

I have the following situation

var stage = new createjs.Stage("canvas");

var parent = new createjs.Container();
parent.x = 50;
parent.rotation = 90;
stage.addChild(parent);

var image = new Image();
image.src = "https://s.imgur.com/images/access/access-logo.png";
image.onload = handleImageLoad;

function handleImageLoad(event) {
    var image = event.target;
    var child = new createjs.Bitmap(image);
    parent.addChild(child);
    stage.update();

    console.assert(child.getTransformedBounds().width === 65);
    console.assert(child.getTransformedBounds().width === 187);
}

See: https://jsfiddle.net/2kr23/48/

The image is 187 wide and 65 high, but after rotating it 90 degrees, I expect it to be 187 high and 65 wide.


Solution

  • EaselJS doesn't currently have a way to get the global bounds of a nested object, however there are a couple of ways you could approach this.

    In your specific case, you could simply get the bounds of the parent: parent.getTransformedBounds().width

    https://jsfiddle.net/2kr23/51/

    A more general approach would be to use localToGlobal() to find the position of the 4 corners in the global coordinate space, then use the min & max extents to get the transformed bounds.

    Something like:

    function getGlobalBounds(child) {
      var tl = child.localToGlobal(0, 0);
      var tr = child.localToGlobal(child.image.width, 0);
      var br = child.localToGlobal(child.image.width, child.image.height);
      var bl = child.localToGlobal(0, child.image.height);
    
      var minX = Math.min(tl.x, tr.x, br.x, bl.x);
      var maxX = Math.max(tl.x, tr.x, br.x, bl.x);
      var minY = Math.min(tl.y, tr.y, br.y, bl.y);
      var maxY = Math.max(tl.y, tr.y, br.y, bl.y);
    
      return new createjs.Rectangle(minX, minY, maxX-minX, maxY-minY);
    }
    

    https://jsfiddle.net/2kr23/58/