smoothSpline.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var _vector = require("../../core/vector");
  2. var v2Distance = _vector.distance;
  3. /**
  4. * Catmull-Rom spline 插值折线
  5. * @module zrender/shape/util/smoothSpline
  6. * @author pissang (https://www.github.com/pissang)
  7. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8. * errorrik (errorrik@gmail.com)
  9. */
  10. /**
  11. * @inner
  12. */
  13. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  14. var v0 = (p2 - p0) * 0.5;
  15. var v1 = (p3 - p1) * 0.5;
  16. return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1;
  17. }
  18. /**
  19. * @alias module:zrender/shape/util/smoothSpline
  20. * @param {Array} points 线段顶点数组
  21. * @param {boolean} isLoop
  22. * @return {Array}
  23. */
  24. function _default(points, isLoop) {
  25. var len = points.length;
  26. var ret = [];
  27. var distance = 0;
  28. for (var i = 1; i < len; i++) {
  29. distance += v2Distance(points[i - 1], points[i]);
  30. }
  31. var segs = distance / 2;
  32. segs = segs < len ? len : segs;
  33. for (var i = 0; i < segs; i++) {
  34. var pos = i / (segs - 1) * (isLoop ? len : len - 1);
  35. var idx = Math.floor(pos);
  36. var w = pos - idx;
  37. var p0;
  38. var p1 = points[idx % len];
  39. var p2;
  40. var p3;
  41. if (!isLoop) {
  42. p0 = points[idx === 0 ? idx : idx - 1];
  43. p2 = points[idx > len - 2 ? len - 1 : idx + 1];
  44. p3 = points[idx > len - 3 ? len - 1 : idx + 2];
  45. } else {
  46. p0 = points[(idx - 1 + len) % len];
  47. p2 = points[(idx + 1) % len];
  48. p3 = points[(idx + 2) % len];
  49. }
  50. var w2 = w * w;
  51. var w3 = w * w2;
  52. ret.push([interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3), interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)]);
  53. }
  54. return ret;
  55. }
  56. module.exports = _default;