Last active
September 26, 2016 16:05
-
-
Save gregtap/4761180 to your computer and use it in GitHub Desktop.
Get bounding box off all objects on a fabric canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
}); |
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
It's much simpler to use object's oCoords field