path.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { __assign, __extends } from "tslib";
  2. import { each, isArray, isObject } from '@antv/util';
  3. import { SVG_ATTR_MAP } from '../constant';
  4. import ShapeBase from './base';
  5. var Path = /** @class */ (function (_super) {
  6. __extends(Path, _super);
  7. function Path() {
  8. var _this = _super !== null && _super.apply(this, arguments) || this;
  9. _this.type = 'path';
  10. _this.canFill = true;
  11. _this.canStroke = true;
  12. return _this;
  13. }
  14. Path.prototype.getDefaultAttrs = function () {
  15. var attrs = _super.prototype.getDefaultAttrs.call(this);
  16. return __assign(__assign({}, attrs), { startArrow: false, endArrow: false });
  17. };
  18. Path.prototype.createPath = function (context, targetAttrs) {
  19. var _this = this;
  20. var attrs = this.attr();
  21. var el = this.get('el');
  22. each(targetAttrs || attrs, function (value, attr) {
  23. if (attr === 'path' && isArray(value)) {
  24. el.setAttribute('d', _this._formatPath(value));
  25. }
  26. else if (attr === 'startArrow' || attr === 'endArrow') {
  27. if (value) {
  28. var id = isObject(value)
  29. ? context.addArrow(attrs, SVG_ATTR_MAP[attr])
  30. : context.getDefaultArrow(attrs, SVG_ATTR_MAP[attr]);
  31. el.setAttribute(SVG_ATTR_MAP[attr], "url(#" + id + ")");
  32. }
  33. else {
  34. el.removeAttribute(SVG_ATTR_MAP[attr]);
  35. }
  36. }
  37. else if (SVG_ATTR_MAP[attr]) {
  38. el.setAttribute(SVG_ATTR_MAP[attr], value);
  39. }
  40. });
  41. };
  42. Path.prototype._formatPath = function (value) {
  43. var newValue = value
  44. .map(function (path) {
  45. return path.join(' ');
  46. })
  47. .join('');
  48. if (~newValue.indexOf('NaN')) {
  49. return '';
  50. }
  51. return newValue;
  52. };
  53. /**
  54. * Get total length of path
  55. * 尽管通过浏览器的 SVGPathElement.getTotalLength() 接口获取的 path 长度,
  56. * 与 Canvas 版本通过数学计算的方式得到的长度有一些细微差异,但最大误差在个位数像素,精度上可以能接受
  57. * @return {number} length
  58. */
  59. Path.prototype.getTotalLength = function () {
  60. var el = this.get('el');
  61. return el ? el.getTotalLength() : null;
  62. };
  63. /**
  64. * Get point according to ratio
  65. * @param {number} ratio
  66. * @return {Point} point
  67. */
  68. Path.prototype.getPoint = function (ratio) {
  69. var el = this.get('el');
  70. var totalLength = this.getTotalLength();
  71. // @see https://github.com/antvis/g/issues/634
  72. if (totalLength === 0) {
  73. return null;
  74. }
  75. var point = el ? el.getPointAtLength(ratio * totalLength) : null;
  76. return point
  77. ? {
  78. x: point.x,
  79. y: point.y,
  80. }
  81. : null;
  82. };
  83. return Path;
  84. }(ShapeBase));
  85. export default Path;
  86. //# sourceMappingURL=path.js.map