Skip to content

Instantly share code, notes, and snippets.

@rezoner
Created October 13, 2012 15:52
Show Gist options
  • Save rezoner/3885097 to your computer and use it in GitHub Desktop.
Save rezoner/3885097 to your computer and use it in GitHub Desktop.
2D Align function
/*
Go to CSS deck to understand how it works
http://cssdeck.com/labs/mtmn9aph/0
*/
function align (boundX, boundY, boundW, boundH, objectW, objectH, boundAlignX, boundAlignY, objectAlignX, objectAlignY) {
var result = [];
if (typeof objectAlignX === "undefined") {
if (boundAlignX == 'left') objectAlignX = 0;
if (boundAlignX == 'right') objectAlignX = objectW;
if (boundAlignX == 'center') objectAlignX = objectW / 2;
}
if (objectAlignX == 'left') objectAlignX = 0;
else if (objectAlignX == 'right') objectAlignX = objectW;
else if (objectAlignX == 'center') objectAlignX = objectW / 2;
if (typeof objectAlignY === "undefined") {
if (boundAlignY == 'top') objectAlignY = 0;
if (boundAlignY == 'bottom') objectAlignY = objectH;
if (boundAlignY == 'center') objectAlignY = objectH / 2;
}
if (objectAlignY == 'top') objectAlignY = 0;
else if (objectAlignY == 'bottom') objectAlignY = objectH;
else if (objectAlignY == 'center') objectAlignY = objectH / 2;
if (boundAlignX == 'left') result[0] = boundX - objectAlignX;
else if (boundAlignX == 'right') result[0] = boundX + boundW - objectAlignX;
else if (boundAlignX == 'center') result[0] = boundX + boundW / 2 - objectAlignX;
else result[0] = boundX + boundAlignX - objectAlignX;
if (boundAlignY == 'top') result[1] = boundY - objectAlignY;
else if (boundAlignY == 'bottom') result[1] = boundY + boundH - objectAlignY;
else if (boundAlignY == 'center') result[1] = boundY + boundH / 2 - objectAlignY;
else result[1] = boundY + boundAlignY - objectAlignY;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment