Skip to content

Instantly share code, notes, and snippets.

@ashblue
Created September 12, 2012 17:06
Show Gist options
  • Save ashblue/3708182 to your computer and use it in GitHub Desktop.
Save ashblue/3708182 to your computer and use it in GitHub Desktop.
Calculates the top left corner of a square from any two x and y points.
/**
* Gets the top left corner of a square from two vertices. Uses nested
* if statements, but its the best way to opimize performance. Point
* parameters can be passed in any order.
* @param {object} point1 Object formatted as { x, y } on a cartesian graph
* @param {object} point1 Object formatted as { x, y } on a cartesian graph
* @returns {object} { x, y } of the top left corner on a square
*/
function getSquareTopLeft (point1, point2) {
// Declare coordinate collection variables
var x, y;
// Optimized top left corner check
if (point1.x > point2.x) {
// start is in bottom right
if (point1.y > point2.y) {
x = point2.x;
y = point2.y;
// Start is in the top right
} else {
x = point2.x;
y = point1.y;
}
} else if (point1.x < point2.x) {
// start is in the top left
if (point1.y < point2.y) {
x = point1.x;
y = point1.y;
// start is in the bottom left
} else {
x = point1.x;
y = point2.y;
}
// No rectangle
} else {
x = point1.x;
y = point1.y;
}
return {
x: x,
y: y
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment