Source: math/Polygon.js

  1. import {Point} from './Point';
  2. import {Utils} from '../utils/Utils';
  3. /**
  4. * @class
  5. * @memberof JC
  6. * @param {JC.Point} points 坐标点数组,可以是JC.Point类型的数组项数组,也可以是连续两个数分别代表x、y坐标的数组。
  7. */
  8. function Polygon(points) {
  9. if (!Utils.isArray(points)) {
  10. points = new Array(arguments.length);
  11. /* eslint-disable */
  12. for (let a = 0; a < points.length; ++a) {
  13. points[a] = arguments[a];
  14. }
  15. }
  16. if (points[0] instanceof Point) {
  17. let p = [];
  18. for (let i = 0, il = points.length; i < il; i++) {
  19. p.push(points[i].x, points[i].y);
  20. }
  21. points = p;
  22. }
  23. this.closed = true;
  24. this.points = points;
  25. }
  26. /**
  27. * 克隆一个属性相同的多边型对象
  28. *
  29. * @return {PIXI.Polygon} 克隆的对象
  30. */
  31. Polygon.prototype.clone = function() {
  32. return new Polygon(this.points.slice());
  33. };
  34. /**
  35. * 检查坐标点是否在多边形内部
  36. *
  37. * @param {number} x 坐标点的x轴坐标
  38. * @param {number} y 坐标点的y轴坐标
  39. * @return {boolean} 是否在多边形内部
  40. */
  41. Polygon.prototype.contains = function(x, y) {
  42. let inside = false;
  43. let length = this.points.length / 2;
  44. for (let i = 0, j = length - 1; i < length; j = i++) {
  45. let xi = this.points[i * 2];
  46. let yi = this.points[i * 2 + 1];
  47. let xj = this.points[j * 2];
  48. let yj = this.points[j * 2 + 1];
  49. let intersect = ((yi > y) !== (yj > y)) &&
  50. (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
  51. if (intersect) {
  52. inside = !inside;
  53. }
  54. }
  55. return inside;
  56. };
  57. export {Polygon};