Skip to content

Instantly share code, notes, and snippets.

@ashblue
Created August 17, 2012 20:04
Show Gist options
  • Save ashblue/3382129 to your computer and use it in GitHub Desktop.
Save ashblue/3382129 to your computer and use it in GitHub Desktop.
Gets the bounding box (an imaginary box) that surrounds an array of squares.
/**
* Creates a bounding box from multiple square objects and returns a rectangle.
* @param {array} squares An array of square objects such as [square1, square2]. Must have
* x, y, width, and height parameters for each object of the sky will fall
* @returns {object} Returns the bounding box of the current squares
*/
function getBoundingBox(squares) {
// Setup basic test properties
var x = Number.POSITIVE_INFINITY;
var y = Number.POSITIVE_INFINITY;
var width = 0;
var height = 0;
var endX = null;
var endY = null;
// Loop through and test all squares to generate x and y coordinates
for (var i = squares.length; i--;) {
if (squares[i].x < x) {
x = squares[i].x;
}
if (squares[i].y < y) {
y = squares[i].y;
}
}
// Loop back through to create the width and height
for (i = squares.length; i--;) {
endX = squares[i].x + squares[i].width - x;
endY = squares[i].y + squares[i].height - y;
if (endX > width) {
width = endX;
}
if (endY > height) {
height = endY;
}
}
return {
x: x,
y: y,
width: width,
height: height
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment