Created
August 28, 2012 21:08
-
-
Save ashblue/3504375 to your computer and use it in GitHub Desktop.
Creates a square bounding box from an array of x and y points
This file contains 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
/** | |
* Create a square bounding box from an array of x and y points | |
* @param {array} A collection of objects with x and y coordinates {x, y} | |
* @returns {object} Square formatted as {x, y, width, height} from the given vertices | |
*/ | |
function getBoundingBox (vertices) { | |
// Setup basic test properties | |
var xMin = Number.POSITIVE_INFINITY, | |
yMin = Number.POSITIVE_INFINITY, | |
xMax = 0, | |
yMax = 0; | |
// Loop through and test all vertices to generate x and y coordinates | |
for (var i = vertices.length; i--;) { | |
// Test x | |
if (vertices[i][0] < xMin) { | |
xMin = vertices[i][0]; | |
} | |
if (vertices[i][0] > xMax) { | |
xMax = vertices[i][0]; | |
} | |
// Test y | |
if (vertices[i][1] < yMin) { | |
yMin = vertices[i][1]; | |
} | |
if (vertices[i][1] > yMax) { | |
yMax = vertices[i][1]; | |
} | |
} | |
// Create a square from the passed data | |
return { | |
x: xMin, | |
y: yMin, | |
width: xMax - xMin, | |
height: yMax - yMin | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment