Skip to content

Instantly share code, notes, and snippets.

@venkatd
Created April 19, 2012 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save venkatd/2424729 to your computer and use it in GitHub Desktop.
Save venkatd/2424729 to your computer and use it in GitHub Desktop.
Rectangle Class
function Rectangle(left, top, width, height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
this._computeCorners();
}
Rectangle.prototype._computeCorners = function() {
this.bottom = this.top + this.height;
this.right = this.left + this.width;
this.lt = this.tl = {left:this.left, top:this.top};
this.ct = this.tc = {left:this.left + this.width / 2, top:this.top};
this.rt = this.tr = {left:this.left + this.width, top:this.top};
this.lc = this.cl = {left:this.left, top:this.top + this.height / 2};
this.c = this.cc = {left:this.left + this.width / 2, top:this.top + this.height / 2};
this.rc = this.cr = {left:this.left + this.width, top:this.top + this.height / 2};
this.lb = this.bl = {left:this.left, top:this.top + this.height};
this.cb = this.bc = {left:this.left + this.width / 2, top:this.top + this.height};
this.rb = this.br = {left:this.left + this.width, top:this.top + this.height};
};
Rectangle.prototype.isAbove = function(rect) {
return this.bottom < rect.top;
};
Rectangle.prototype.isBelow = function(rect) {
return this.top > rect.bottom;
};
Rectangle.prototype.isRight = function(rect) {
return this.left > rect.right;
};
Rectangle.prototype.isLeft = function(rect) {
return this.right < rect.left;
};
Rectangle.prototype.overlaps = function(rect) {
var noOverlap = this.isAbove(rect) || this.isBelow(rect)
|| this.isRight(rect) || this.isLeft(rect);
return !noOverlap;
};
Rectangle.prototype.translate = function(deltaX, deltaY) {
return new Rectangle(this.left + deltaX, this.top + deltaY, this.width, this.height);
};
Rectangle.prototype.translatePoint = function(pointName, thatRect, thatPoint) {
var thisPoint = this[pointName];
var thatPoint = thatRect[thatPoint];
//without any further translation, the top-left of the source will get aligned to target
var translate = {
left: this.left - thisPoint.left,
top: this.top - thisPoint.top
};
return new Rectangle(thatPoint.left + translate.left, thatPoint.top + translate.top, this.width, this.height);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment