# lib/goog/math/rect.js

    1// Copyright 2006 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415/**16 * @fileoverview A utility class for representing rectangles.17 */1819goog.provide('goog.math.Rect');2021goog.require('goog.math.Box');22goog.require('goog.math.Coordinate');23goog.require('goog.math.Size');24252627/**28 * Class for representing rectangular regions.29 * @param {number} x Left.30 * @param {number} y Top.31 * @param {number} w Width.32 * @param {number} h Height.33 * @constructor34 */35goog.math.Rect = function(x, y, w, h) {36  /** @type {number} */37  this.left = x;3839  /** @type {number} */40  this.top = y;4142  /** @type {number} */43  this.width = w;4445  /** @type {number} */46  this.height = h;47};484950/**51 * @return {!goog.math.Rect} A new copy of this Rectangle.52 */53goog.math.Rect.prototype.clone = function() {54  return new goog.math.Rect(this.left, this.top, this.width, this.height);55};565758/**59 * Returns a new Box object with the same position and dimensions as this60 * rectangle.61 * @return {!goog.math.Box} A new Box representation of this Rectangle.62 */63goog.math.Rect.prototype.toBox = function() {64  var right = this.left + this.width;65  var bottom = this.top + this.height;66  return new goog.math.Box(this.top,67                           right,68                           bottom,69                           this.left);70};717273/**74 * Creates a new Rect object with the same position and dimensions as a given75 * Box.  Note that this is only the inverse of toBox if left/top are defined.76 * @param {goog.math.Box} box A box.77 * @return {!goog.math.Rect} A new Rect initialized with the box's position78 *     and size.79 */80goog.math.Rect.createFromBox = function(box) {81  return new goog.math.Rect(box.left, box.top,82      box.right - box.left, box.bottom - box.top);83};848586if (goog.DEBUG) {87  /**88   * Returns a nice string representing size and dimensions of rectangle.89   * @return {string} In the form (50, 73 - 75w x 25h).90   * @override91   */92  goog.math.Rect.prototype.toString = function() {93    return '(' + this.left + ', ' + this.top + ' - ' + this.width + 'w x ' +94           this.height + 'h)';95  };96}979899/**100 * Compares rectangles for equality.101 * @param {goog.math.Rect} a A Rectangle.102 * @param {goog.math.Rect} b A Rectangle.103 * @return {boolean} True iff the rectangles have the same left, top, width,104 *     and height, or if both are null.105 */106goog.math.Rect.equals = function(a, b) {107  if (a == b) {108    return true;109  }110  if (!a || !b) {111    return false;112  }113  return a.left == b.left && a.width == b.width &&114         a.top == b.top && a.height == b.height;115};116117118/**119 * Computes the intersection of this rectangle and the rectangle parameter.  If120 * there is no intersection, returns false and leaves this rectangle as is.121 * @param {goog.math.Rect} rect A Rectangle.122 * @return {boolean} True iff this rectangle intersects with the parameter.123 */124goog.math.Rect.prototype.intersection = function(rect) {125  var x0 = Math.max(this.left, rect.left);126  var x1 = Math.min(this.left + this.width, rect.left + rect.width);127128  if (x0 <= x1) {129    var y0 = Math.max(this.top, rect.top);130    var y1 = Math.min(this.top + this.height, rect.top + rect.height);131132    if (y0 <= y1) {133      this.left = x0;134      this.top = y0;135      this.width = x1 - x0;136      this.height = y1 - y0;137138      return true;139    }140  }141  return false;142};143144145/**146 * Returns the intersection of two rectangles. Two rectangles intersect if they147 * touch at all, for example, two zero width and height rectangles would148 * intersect if they had the same top and left.149 * @param {goog.math.Rect} a A Rectangle.150 * @param {goog.math.Rect} b A Rectangle.151 * @return {goog.math.Rect} A new intersection rect (even if width and height152 *     are 0), or null if there is no intersection.153 */154goog.math.Rect.intersection = function(a, b) {155  // There is no nice way to do intersection via a clone, because any such156  // clone might be unnecessary if this function returns null.  So, we duplicate157  // code from above.158159  var x0 = Math.max(a.left, b.left);160  var x1 = Math.min(a.left + a.width, b.left + b.width);161162  if (x0 <= x1) {163    var y0 = Math.max(a.top, b.top);164    var y1 = Math.min(a.top + a.height, b.top + b.height);165166    if (y0 <= y1) {167      return new goog.math.Rect(x0, y0, x1 - x0, y1 - y0);168    }169  }170  return null;171};172173174/**175 * Returns whether two rectangles intersect. Two rectangles intersect if they176 * touch at all, for example, two zero width and height rectangles would177 * intersect if they had the same top and left.178 * @param {goog.math.Rect} a A Rectangle.179 * @param {goog.math.Rect} b A Rectangle.180 * @return {boolean} Whether a and b intersect.181 */182goog.math.Rect.intersects = function(a, b) {183  return (a.left <= b.left + b.width && b.left <= a.left + a.width &&184      a.top <= b.top + b.height && b.top <= a.top + a.height);185};186187188/**189 * Returns whether a rectangle intersects this rectangle.190 * @param {goog.math.Rect} rect A rectangle.191 * @return {boolean} Whether rect intersects this rectangle.192 */193goog.math.Rect.prototype.intersects = function(rect) {194  return goog.math.Rect.intersects(this, rect);195};196197198/**199 * Computes the difference regions between two rectangles. The return value is200 * an array of 0 to 4 rectangles defining the remaining regions of the first201 * rectangle after the second has been subtracted.202 * @param {goog.math.Rect} a A Rectangle.203 * @param {goog.math.Rect} b A Rectangle.204 * @return {!Array.<!goog.math.Rect>} An array with 0 to 4 rectangles which205 *     together define the difference area of rectangle a minus rectangle b.206 */207goog.math.Rect.difference = function(a, b) {208  var intersection = goog.math.Rect.intersection(a, b);209  if (!intersection || !intersection.height || !intersection.width) {210    return [a.clone()];211  }212213  var result = [];214215  var top = a.top;216  var height = a.height;217218  var ar = a.left + a.width;219  var ab = a.top + a.height;220221  var br = b.left + b.width;222  var bb = b.top + b.height;223224  // Subtract off any area on top where A extends past B225  if (b.top > a.top) {226    result.push(new goog.math.Rect(a.left, a.top, a.width, b.top - a.top));227    top = b.top;228    // If we're moving the top down, we also need to subtract the height diff.229    height -= b.top - a.top;230  }231  // Subtract off any area on bottom where A extends past B232  if (bb < ab) {233    result.push(new goog.math.Rect(a.left, bb, a.width, ab - bb));234    height = bb - top;235  }236  // Subtract any area on left where A extends past B237  if (b.left > a.left) {238    result.push(new goog.math.Rect(a.left, top, b.left - a.left, height));239  }240  // Subtract any area on right where A extends past B241  if (br < ar) {242    result.push(new goog.math.Rect(br, top, ar - br, height));243  }244245  return result;246};247248249/**250 * Computes the difference regions between this rectangle and {@code rect}. The251 * return value is an array of 0 to 4 rectangles defining the remaining regions252 * of this rectangle after the other has been subtracted.253 * @param {goog.math.Rect} rect A Rectangle.254 * @return {!Array.<!goog.math.Rect>} An array with 0 to 4 rectangles which255 *     together define the difference area of rectangle a minus rectangle b.256 */257goog.math.Rect.prototype.difference = function(rect) {258  return goog.math.Rect.difference(this, rect);259};260261262/**263 * Expand this rectangle to also include the area of the given rectangle.264 * @param {goog.math.Rect} rect The other rectangle.265 */266goog.math.Rect.prototype.boundingRect = function(rect) {267  // We compute right and bottom before we change left and top below.268  var right = Math.max(this.left + this.width, rect.left + rect.width);269  var bottom = Math.max(this.top + this.height, rect.top + rect.height);270271  this.left = Math.min(this.left, rect.left);272  this.top = Math.min(this.top, rect.top);273274  this.width = right - this.left;275  this.height = bottom - this.top;276};277278279/**280 * Returns a new rectangle which completely contains both input rectangles.281 * @param {goog.math.Rect} a A rectangle.282 * @param {goog.math.Rect} b A rectangle.283 * @return {goog.math.Rect} A new bounding rect, or null if either rect is284 *     null.285 */286goog.math.Rect.boundingRect = function(a, b) {287  if (!a || !b) {288    return null;289  }290291  var clone = a.clone();292  clone.boundingRect(b);293294  return clone;295};296297298/**299 * Tests whether this rectangle entirely contains another rectangle or300 * coordinate.301 *302 * @param {goog.math.Rect|goog.math.Coordinate} another The rectangle or303 *     coordinate to test for containment.304 * @return {boolean} Whether this rectangle contains given rectangle or305 *     coordinate.306 */307goog.math.Rect.prototype.contains = function(another) {308  if (another instanceof goog.math.Rect) {309    return this.left <= another.left &&310           this.left + this.width >= another.left + another.width &&311           this.top <= another.top &&312           this.top + this.height >= another.top + another.height;313  } else { // (another instanceof goog.math.Coordinate)314    return another.x >= this.left &&315           another.x <= this.left + this.width &&316           another.y >= this.top &&317           another.y <= this.top + this.height;318  }319};320321322/**323 * @param {!goog.math.Coordinate} point A coordinate.324 * @return {number} The squared distance between the point and the closest325 *     point inside the rectangle. Returns 0 if the point is inside the326 *     rectangle.327 */328goog.math.Rect.prototype.squaredDistance = function(point) {329  var dx = point.x < this.left ?330      this.left - point.x : Math.max(point.x - (this.left + this.width), 0);331  var dy = point.y < this.top ?332      this.top - point.y : Math.max(point.y - (this.top + this.height), 0);333  return dx * dx + dy * dy;334};335336337/**338 * @param {!goog.math.Coordinate} point A coordinate.339 * @return {number} The distance between the point and the closest point340 *     inside the rectangle. Returns 0 if the point is inside the rectangle.341 */342goog.math.Rect.prototype.distance = function(point) {343  return Math.sqrt(this.squaredDistance(point));344};345346347/**348 * @return {!goog.math.Size} The size of this rectangle.349 */350goog.math.Rect.prototype.getSize = function() {351  return new goog.math.Size(this.width, this.height);352};353354355/**356 * @return {!goog.math.Coordinate} A new coordinate for the top-left corner of357 *     the rectangle.358 */359goog.math.Rect.prototype.getTopLeft = function() {360  return new goog.math.Coordinate(this.left, this.top);361};362363364/**365 * @return {!goog.math.Coordinate} A new coordinate for the center of the366 *     rectangle.367 */368goog.math.Rect.prototype.getCenter = function() {369  return new goog.math.Coordinate(370      this.left + this.width / 2, this.top + this.height / 2);371};372373374/**375 * @return {!goog.math.Coordinate} A new coordinate for the bottom-right corner376 *     of the rectangle.377 */378goog.math.Rect.prototype.getBottomRight = function() {379  return new goog.math.Coordinate(380      this.left + this.width, this.top + this.height);381};382383384/**385 * Rounds the fields to the next larger integer values.386 * @return {!goog.math.Rect} This rectangle with ceil'd fields.387 */388goog.math.Rect.prototype.ceil = function() {389  this.left = Math.ceil(this.left);390  this.top = Math.ceil(this.top);391  this.width = Math.ceil(this.width);392  this.height = Math.ceil(this.height);393  return this;394};395396397/**398 * Rounds the fields to the next smaller integer values.399 * @return {!goog.math.Rect} This rectangle with floored fields.400 */401goog.math.Rect.prototype.floor = function() {402  this.left = Math.floor(this.left);403  this.top = Math.floor(this.top);404  this.width = Math.floor(this.width);405  this.height = Math.floor(this.height);406  return this;407};408409410/**411 * Rounds the fields to nearest integer values.412 * @return {!goog.math.Rect} This rectangle with rounded fields.413 */414goog.math.Rect.prototype.round = function() {415  this.left = Math.round(this.left);416  this.top = Math.round(this.top);417  this.width = Math.round(this.width);418  this.height = Math.round(this.height);419  return this;420};421422423/**424 * Translates this rectangle by the given offsets. If a425 * {@code goog.math.Coordinate} is given, then the left and top values are426 * translated by the coordinate's x and y values. Otherwise, top and left are427 * translated by {@code tx} and {@code opt_ty} respectively.428 * @param {number|goog.math.Coordinate} tx The value to translate left by or the429 *     the coordinate to translate this rect by.430 * @param {number=} opt_ty The value to translate top by.431 * @return {!goog.math.Rect} This rectangle after translating.432 */433goog.math.Rect.prototype.translate = function(tx, opt_ty) {434  if (tx instanceof goog.math.Coordinate) {435    this.left += tx.x;436    this.top += tx.y;437  } else {438    this.left += tx;439    if (goog.isNumber(opt_ty)) {440      this.top += opt_ty;441    }442  }443  return this;444};445446447/**448 * Scales this rectangle by the given scale factors. The left and width values449 * are scaled by {@code sx} and the top and height values are scaled by450 * {@code opt_sy}.  If {@code opt_sy} is not given, then all fields are scaled451 * by {@code sx}.452 * @param {number} sx The scale factor to use for the x dimension.453 * @param {number=} opt_sy The scale factor to use for the y dimension.454 * @return {!goog.math.Rect} This rectangle after scaling.455 */456goog.math.Rect.prototype.scale = function(sx, opt_sy) {457  var sy = goog.isNumber(opt_sy) ? opt_sy : sx;458  this.left *= sx;459  this.width *= sx;460  this.top *= sy;461  this.height *= sy;462  return this;463};