c8d6bef78d2e9cac5f434c4c82510983782d7029c007c7c6264e37aecce24da4ca743ba37fbd560808b48b209290ec93ae710954ea869694484ea1763f0320 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import PathProxy from '../../core/PathProxy';
  2. export function buildPath(ctx: CanvasRenderingContext2D | PathProxy, shape: {
  3. x: number
  4. y: number
  5. width: number
  6. height: number
  7. r?: number | number[]
  8. }) {
  9. let x = shape.x;
  10. let y = shape.y;
  11. let width = shape.width;
  12. let height = shape.height;
  13. let r = shape.r;
  14. let r1;
  15. let r2;
  16. let r3;
  17. let r4;
  18. // Convert width and height to positive for better borderRadius
  19. if (width < 0) {
  20. x = x + width;
  21. width = -width;
  22. }
  23. if (height < 0) {
  24. y = y + height;
  25. height = -height;
  26. }
  27. if (typeof r === 'number') {
  28. r1 = r2 = r3 = r4 = r;
  29. }
  30. else if (r instanceof Array) {
  31. if (r.length === 1) {
  32. r1 = r2 = r3 = r4 = r[0];
  33. }
  34. else if (r.length === 2) {
  35. r1 = r3 = r[0];
  36. r2 = r4 = r[1];
  37. }
  38. else if (r.length === 3) {
  39. r1 = r[0];
  40. r2 = r4 = r[1];
  41. r3 = r[2];
  42. }
  43. else {
  44. r1 = r[0];
  45. r2 = r[1];
  46. r3 = r[2];
  47. r4 = r[3];
  48. }
  49. }
  50. else {
  51. r1 = r2 = r3 = r4 = 0;
  52. }
  53. let total;
  54. if (r1 + r2 > width) {
  55. total = r1 + r2;
  56. r1 *= width / total;
  57. r2 *= width / total;
  58. }
  59. if (r3 + r4 > width) {
  60. total = r3 + r4;
  61. r3 *= width / total;
  62. r4 *= width / total;
  63. }
  64. if (r2 + r3 > height) {
  65. total = r2 + r3;
  66. r2 *= height / total;
  67. r3 *= height / total;
  68. }
  69. if (r1 + r4 > height) {
  70. total = r1 + r4;
  71. r1 *= height / total;
  72. r4 *= height / total;
  73. }
  74. ctx.moveTo(x + r1, y);
  75. ctx.lineTo(x + width - r2, y);
  76. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  77. ctx.lineTo(x + width, y + height - r3);
  78. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  79. ctx.lineTo(x + r4, y + height);
  80. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  81. ctx.lineTo(x, y + r1);
  82. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  83. }