modeling/src/primitives/rectangle.js

  1. const vec2 = require('../maths/vec2')
  2. const geom2 = require('../geometries/geom2')
  3. const { isNumberArray } = require('./commonChecks')
  4. /**
  5. * Construct an axis-aligned rectangle in two dimensional space with four sides at right angles.
  6. * @param {Object} [options] - options for construction
  7. * @param {Array} [options.center=[0,0]] - center of rectangle
  8. * @param {Array} [options.size=[2,2]] - dimension of rectangle, width and length
  9. * @returns {geom2} new 2D geometry
  10. * @alias module:modeling/primitives.rectangle
  11. *
  12. * @example
  13. * let myshape = rectangle({size: [10, 20]})
  14. */
  15. const rectangle = (options) => {
  16. const defaults = {
  17. center: [0, 0],
  18. size: [2, 2]
  19. }
  20. const { center, size } = Object.assign({}, defaults, options)
  21. if (!isNumberArray(center, 2)) throw new Error('center must be an array of X and Y values')
  22. if (!isNumberArray(size, 2)) throw new Error('size must be an array of X and Y values')
  23. if (!size.every((n) => n >= 0)) throw new Error('size values must be positive')
  24. // if any size is zero return empty geometry
  25. if (size[0] === 0 || size[1] === 0) return geom2.create()
  26. const point = [size[0] / 2, size[1] / 2]
  27. const pswap = [point[0], -point[1]]
  28. const points = [
  29. vec2.subtract(vec2.create(), center, point),
  30. vec2.add(vec2.create(), center, pswap),
  31. vec2.add(vec2.create(), center, point),
  32. vec2.subtract(vec2.create(), center, pswap)
  33. ]
  34. return geom2.fromPoints(points)
  35. }
  36. module.exports = rectangle