Skip to content

Instantly share code, notes, and snippets.

@gregtap
Last active September 26, 2016 16:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gregtap/4761180 to your computer and use it in GitHub Desktop.
Save gregtap/4761180 to your computer and use it in GitHub Desktop.
Get bounding box off all objects on a fabric canvas
getBoardBoundingBox: function(canvas) {
var minX = Number.MAX_VALUE;
var maxX = Number.MIN_VALUE;
var minY = Number.MAX_VALUE;
var maxY = Number.MIN_VALUE;
canvas.forEachObject(function(o){
var rad = o.angle * Math.PI/180;
var w = o.width * o.scaleX;
var h = o.height * o.scaleY;
// xmax = x * w/2 * |cos(theta)| + h/2 * |sin(theta)|
var omaxX = o.left +((w/2) * Math.abs(Math.cos(rad))) + ((h/2) * Math.abs(Math.sin(rad)));
var ominX = o.left - (omaxX - o.left);
// ymax = y * w/2 * |sin(theta)| + h/2 * |cos(theta)|
var omaxY = o.top + ((w/2) * Math.abs(Math.sin(rad))) + ((h/2) * Math.abs(Math.cos(rad)));
var ominY = o.top - (omaxY - o.top);
if (ominX < minX)
minX = ominX;
if (omaxX > maxX)
maxX = omaxX;
if (ominY < minY)
minY = ominY;
if (omaxY > maxY)
maxY = omaxY;
});
var box = {
"x": minX,
"y": minY,
"w": maxX - minX,
"h": maxY - minY
};
return box;
}
});
@everdance
Copy link

It's much simpler to use object's oCoords field

 canvas.forEachObject (o) ->
    cords = o.oCoords
    omaxX = Math.max(cords.tl.x, cords.tr.x, cords.bl.x, cords.br.x)
    ominX = Math.min(cords.tl.x, cords.tr.x, cords.bl.x, cords.br.x)
    omaxY = Math.max(cords.tl.y, cords.tr.y, cords.bl.y, cords.br.y)
    ominY = Math.min(cords.tl.y, cords.tr.y, cords.bl.y, cords.br.y)

    if (ominX < minX)
        minX = ominX
    if (omaxX > maxX)
        maxX = omaxX
    if (ominY < minY)
        minY = ominY
    if (omaxY > maxY)
        maxY = omaxY

@davidtorroija
Copy link

davidtorroija commented Sep 26, 2016

In my case the @coulix solution it's better than @everdance because you can calculate the bounding box without have the items already pushed in the canvas, because the only way to have the oCoords is to have the item inserted in the canvas, and I want to prepare the canvas size before have the items inserted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment